can someone help me clear these errors - java

I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}

A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.

Related

How to eliminate a nested for loop to get O(n)?

In the code below I have a double for loop resulting in a time complexity of O^2 in method getResponse(). This code prompts the user for a 10 integer sequence string and an uppercase sensitive pin. It then converts the pin to numbers on a phone pad ie. [ABC] --> 2, [DEF] --> 3. Lastly a response array is generated with each digit of the new phone pin corresponding to indexes of sequence. So input "0123456789","HAM", response = "426"
import java.util.Scanner;
public class Test {
public static final int SEQ_DIGITS = 10;
public static final String ERR_SEQ = "Invalid sequence";
public static final String ERR_PIN = "Invalid PIN";
public static int letterToPhone(char c) {
int phoneNumber = 0;
if (Character.toString(c).matches("[ABC]")) {
phoneNumber = 2;
} else if (Character.toString(c).matches("[DEF]")) {
phoneNumber = 3;
} else if (Character.toString(c).matches("[GHI]")) {
phoneNumber = 4;
} else if (Character.toString(c).matches("[JKL]")) {
phoneNumber = 5;
} else if (Character.toString(c).matches("[MNO]")) {
phoneNumber = 6;
} else if (Character.toString(c).matches("[PQRS]")) {
phoneNumber = 7;
} else if (Character.toString(c).matches("[TUV]")) {
phoneNumber = 8;
} else if (Character.toString(c).matches("[WXYZ]")) {
phoneNumber = 9;
}
return phoneNumber;
}
public static int[] getResponse(String pin, int[] values) {
int[] response = new int[pin.length()];
for(int i = 0; i < pin.length(); i++) {
for (int j = 0; j < values.length; j++) {
int x = letterToPhone(pin.charAt(i));
if(x == j) {
response[i] = values[j];
}
}
}
return response;
}
public static boolean stringIsLengthK(String s, int k) {
boolean isLength = false;
if (s.length() == k) {
isLength = true;
}
return isLength;
}
public static boolean allDigits(String s) {
boolean isDigit = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isDigit(s.charAt(i)))) {
isDigit = false;
break;
}
}
return isDigit;
}
public static boolean allUppercaseLetters(String s) {
boolean isUpper = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isUpperCase(s.charAt(i)))) {
isUpper = false;
break;
}
}
return isUpper;
}
public static int[] digitStringToIntArray(String s) {
int[] arrayS = new int[s.length()];
for(int i = 0; i < arrayS.length; i++) {
for(int j = 0; j < SEQ_DIGITS; j++) {
if (((int) s.charAt(i) - 48) == j) {
arrayS[i] = j;
}
}
}
return arrayS;
}
public static int countValues(int value, int[] values) {
int count = 0;
for(int i = 0; i < values.length; i++) {
if(value == values[i]) {
count++;
}
}
return count;
}
public static int numPossible(int[] response, int[] values) {
int product = 1;
int[] count = new int[response.length];
for (int i = 0; i < count.length; i++) {
count[i] = countValues(response[i], values);
}
for(int i=0; i<response.length; i++){
product = product * count[i];
}
return product;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.printf("Enter value sequence: ");
final String seq = in.nextLine();
System.out.printf("Enter PIN: ");
final String pin = in.nextLine();
if (!(allUppercaseLetters(pin))) {
throw new AssertionError(ERR_PIN);
} else if (!(allDigits(seq)) || !(stringIsLengthK(seq, SEQ_DIGITS))) {
throw new AssertionError(ERR_SEQ);
}
int[] seqArray = new int[SEQ_DIGITS];
seqArray = digitStringToIntArray(seq);
int[] response = new int[SEQ_DIGITS];
response = getResponse(pin, seqArray);
System.out.printf("Response: ");
for (int i = 0; i < response.length; i++) {
System.out.printf("%d", response[i]);
}
System.out.printf("%n");
numPossible(response, seqArray);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
}
I want to be to able to accommodate larger sequence numbers without a scaling of n^2. Is there a way to change the for loop to instead compare the int x = letterToPhone(pin.charAt(i)); value in getResponse() to a range of integers such as "[0-9]"
One easy optimization of constant factors is to move the call to letterToPhone() out of the inner loop.
And yes, you can compare the x value to a range, eliminating the need for the inner loop.
for(int i = 0; i < pin.length(); i++) {
int x = letterToPhone(pin.charAt(i));
if ( (0 <= x) && (x < values.length)) {
response[i] = values[x];
}
}
Another optimization of constant factors would be to replace all the function calls in letterToPhone() with a switch statement. The compiler may choose to optimize that into a table lookup.

Why else statement is executing although if statement is true?

import java.util.Scanner;
class candidate {
public String name;
public int count;
public candidate(String name) {
super();
this.name = name;
}
}
public class DayScholar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
candidate[] candidates = new candidate[3];
candidates[0] = new candidate("vikas");
candidates[1] = new candidate("ganesh");
candidates[2] = new candidate("teja");
System.out.print("No. of voters : ");
int voters = in.nextInt();
in.nextLine();
for (int i = 0; i < voters; i++) {
System.out.print("vote : ");
String name = in.nextLine().toLowerCase();
for (int j = 0; j < 3; j++) {
Here is the code, although if the statement is true else is also executing. How to check the condition
if (name.equals(candidates[j].name)) {
candidates[j].count++;
} else { **//problem here**
System.out.println("N");
break;
}
}
}
int highest = 0;
String winner = "";
for (int i = 0; i < 3; i++) {
if (candidates[i].count > highest) {
highest = candidates[i].count;
winner = candidates[i].name;
} else if (candidates[i].count == highest) {
winner += ("\n" + candidates[i].name);
}
}
System.out.println(winner);
}
}
Assuming the user enters a valid name, the following loop will increment the count field on the candidate with the matching name, and print N for the other 2 candidates.
for (int j = 0; j < 3; j++) {
if (name.equals(candidates[j].name)) {
candidates[j].count++;
} else {
System.out.println("N");
break;
}
}
To fix, you need the loop to just set the index of the matching candidate, then do the increment or printing after the loop:
int matchingIndex = -1; // -1 = not found
for (int j = 0; j < 3; j++) {
if (name.equals(candidates[j].name)) {
matchingIndex = j;
break;
}
}
if (matchingIndex == -1) {
System.out.println("N");
} else {
candidates[matchingIndex].count++;
}

string length, number of capitals, and number of numbers in a string

I want to check if a string has 8 or more characters, and if it has 1 capital letter and 1 number.
This is my code:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 1;
int captialCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 1;
if (numberCharaters >= 8 && numberNumbers >= 1 && numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}
and this is the error message I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at passwordtest.main(passwordtest.java:23)
My input was: Test1
What am I doing wrong? I've been trying to figure out where the java.lang.StringIndexOutOfBoundsException: comes from.
Your program has some mistakes.
You should have initialized numberCount to 0 to avoid having to subtract later, and avoid having to create another variable. Also the error you're getting is because of the <=, since there is no string element = to the length of the string, i.e index is from 0 to length - 1.
int numberCount = 0;
for (int i = 0; i < numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
Then, for the capital count you made the same mistake, I would also take into account the advice in the comments to improve the loops.
You are making a minor mistake.
Length = Actual number of elements(characters).
Index = starts from 0 and ends at length-1.
Your code should be look like this:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 0;
for (int i = 0; i <= numberCharaters-1; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 0;
int captialCount = 0;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 0;
if (numberCharaters >= 8 && numberNumbers >= 1 &&
numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}
import java.util.*;
public class password
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("enter the password : ");
String s=sc.nextLine();
int l=s.length();
int k=0,k1=0;
if(l>=8)
{
for(int i=0;i<l;i++)
{
if(Character.isLetter(s.charAt(i)))
{
if(Character.isUpperCase(s.charAt(i)))
{
k++;
}
}
else
{
if(Character.isDigit(s.charAt(i)))
{
k1++;
}
}
}
if(k>0&&k1>0)
{
System.out.println("Password is strong enough");
}
else
{
System.out.println("Password shoud contain atleast capital letter and one number");
}
}
else
{
System.out.println("Password shoud contain atleast capital letter,one number and shoud have length of 8 or more");
}
}
}

Currently compiling, but receiving nothing but end to program?

import java.util.Scanner;
public class PD {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter your number: " );
int number = input.nextInt();
for (int count = 2; count < number; count++) {
String blank = "";
String Snumber = count + blank;
if (isPalindromic(count) && isPrime(count) &&
isPalindromic((int)(Snumber.length())) &&
isPrime((int)(Snumber.length()))){
System.out.println( count + "is double palidromic prime");
}
else
continue;
}
}
// method to find palindromic
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
for (int i = 0, q = 1; i <= (convert.length()/2 - 1); i++, q++) {
if (convert.substring(i,q) == convert.substring(convert.length() - q, convert.length() - i)){
return true;
}
}
return false;
}
// method to find prime
public static boolean isPrime(int count ) {
for (int divisor = 2; divisor <= count/2; divisor++) {
if (count % divisor == 0) {
return false;
}
}
return true;
}
}
Currently the thing compiles and ask for input, but it always results in nothing.
Does someone see something wrong with my program that is obvious wrong.
Overall, the program receives input and has to look through values 2 until it hits the value the user wants and print the ones that follow the if statement.
Your isPalindromic method is not functioning properly. It is not returning true for palindromic numbers. Change it to this:
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
int n = convert.length();
for (int i = 0; i < (n / 2 + 1); i++) {
if (convert.charAt(i) != convert.charAt(n - i - 1)) {
return false;
}
}
return true;
}

Can't proceed with main method after do while loop

I am new to Java and working on simple task - TicTacToe console game. Today I've faced a problem that I can't proceed with the main method after do while loop. The project has two classes - Main and Field. Field is responsive for all game field updates. I'm calling Field methods in do while loop of the main method but when the result is on the loop has to be finished and the main method has to go on(it should ask if the user wants to play again). Unfortunately the programm stops after do while loop.
Here is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
private static char playerSym, compSym;
private static int Sym;
public static int playerChoice;
public static boolean result;
public static void main(String args[]) throws IOException {
Field field = new Field();
// start of the game
System.out.println("Let`s play");
System.out.println("Choose your symbol please");
System.out.println("0='O', 1='X'");
Scanner sc = new Scanner(System.in);
Sym = sc.nextInt();
while (Sym != 0 & Sym != 1) {
System.out
.println("The symbol you entered is incorrect, please repeat");
System.out.println("0='O', 1='X'");
Sym = sc.nextInt();
}
// setting player character
if (Sym == 1) {
playerSym = 'X';
compSym = 'O';
} else if (Sym == 0) {
playerSym = 'O';
compSym = 'Х';
}
System.out.println("There is a game field");
System.out.println("Please choose the cell number you`d like to fill with " + playerSym);
field.firstShowFields();
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
} while (result==false);
System.out.println("Want to play once more? Y-Yes, N-No");
char answer = (char) System.in.read();
switch (answer) {
case 'Y':
System.out.println("Restarting the game");
break;
case 'N':
System.out.println("Thank you! Bye-Bye!");
break;
default:
break;
}
}
}
public class Field {
public static final int FIELD_SIZE = 3;
// private static final char DEFAULT_CHAR=' ';
public char[][] fields;
public boolean result = true;
public char playerSym;
public Field() {
fields = new char[FIELD_SIZE][FIELD_SIZE];
}
public void firstShowFields() {
int cellValue = 1;
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + cellValue + "]");
cellValue++;
}
System.out.println();
}
}
public char[][] updateFields(int choice, char sym) {
playerSym = sym;
int cellValue = 1;
int playerChoice = choice;
do {
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
if (playerChoice == cellValue) {
fields[i][j] = (char) playerSym;
} else if (fields[i][j] == (char) playerSym) {
fields[i][j] = (char) playerSym;
} else {
fields[i][j] = (char) ('0' + cellValue);
}
cellValue++;
}
}
this.checkWin(fields, playerSym);
return fields;
} while (this.checkWin(fields, playerSym) == false);
}
public void showFields(char[][] fields) {
this.fields = fields;
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + fields[i][j] + "]");
}
System.out.println();
}
}
public boolean checkWin(char[][] field, char playerSym) {
char[][] checkField = field;
this.playerSym = playerSym;
// checkline
if (((checkField[0][0] == checkField[0][1]) && (checkField[0][1] == checkField[0][2]))
|| ((checkField[1][0] == checkField[1][1]) && (checkField[1][1] == checkField[1][2]))
|| ((checkField[2][0] == checkField[2][1]) && (checkField[2][1] == checkField[2][2]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return true;
}
// checkraw
else if (((checkField[0][0] == checkField[1][0]) && (checkField[1][0] == checkField[2][0]))
|| ((checkField[0][1] == checkField[1][1]) && (checkField[1][1] == checkField[2][1]))
|| ((checkField[0][2] == checkField[1][2]) && (checkField[1][2] == checkField[2][2]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return result = true;
} // checkdiagonal
else if (((checkField[0][0] == checkField[1][1]) && (checkField[1][1] == checkField[2][2]))
|| ((checkField[0][2] == checkField[1][1]) && (checkField[1][1] == checkField[2][0]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return result = true;
}
return false;
}
}
Here is an infinite loop:
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
} while (result==false);
result is never updated so the while (result==false); will never fail as long as it was true the first time. You may try modifying it like below:
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
result = field.checkWin(field.fields, playerSym);
} while (result==false);
Also, it is not a good practice to pass fields that are already attached to the instance to instance methods. You can remove the parameter char[][] field from the checkWin method and simply have it operate on the instance variable fields. But that's not the cause of your loop issue.
As user506 points out the only reason why it won't progress past the loop is because the boolean result is never set to true.
Why do you have 2 classes to separate the main method?

Categories