Incompatible Types in If Statement - java

I am getting an incompatible types error message in my if statement. The variables "answer" and "input2" are both integers so I am not sure how the two are incompatible. Any help or insight would be much appreciated!
public static void addingGame()
{
System.out.print("\n");
System.out.println("********* Part 2: Adding Numbers **********");
System.out.print("\n");
Scanner inputReader = new Scanner(System.in);
System.out.print("Would you like to add some numbers?(y/n)");
String input = inputReader.next();
while (!input.equals("y") && !input.equals("n"))
{
System.out.print("I need a y/n: ");
input = inputReader.next();
}
while (input.equals("y"))
{
Random numberGenerator = new Random();
int randomNumber1 = numberGenerator.nextInt(10);
int randomNumber2 = numberGenerator.nextInt(10);
int answer = ((randomNumber1) + (randomNumber2));
System.out.print( randomNumber1 + " + " + randomNumber2 + " =: ");
int input2 = inputReader.nextInt();
if (answer = input2)
{
System.out.print("Right! " + answer + " is the answer.");
}
else
{
System.out.print("Sorry, " + answer + " is the answer.");
}
System.out.print("Would you like to play again?(y/n)");
input = inputReader.next();
while (!input.equals("y") && !input.equals("n"))
{
System.out.print("Sorry - I need a y/n: ");
input = inputReader.next();
}
}
System.out.print("\n");
System.out.print("Thanks - Let's move on to Part 3...");

You're using the assignment operator = when you wanted to compare the values (==). Change
if (answer = input2)
to
if (answer == input2)
The error came from the fact that the result of the assignment is still an int, where as the if condition expects a boolean, which == provides.

Related

How do I use a 'for' loop to check for certain digits in an input?

I'm new to java and very new to using loops, so far I have been working on a problem for my class to make a program that checks if the user inputs a variation of correct numbers randomly generated, but it says that lotteryNumberString cant be found once the loop starts. Any tips on how to fix it?
import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for(int i=0; i < 3; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);
String lotteryNumberString = Integer.toString(lotteryNumberDigit);
}
String firstNumber = lotteryNumberString.substring(0,0);
String secondNumber = lotteryNumberString.substring(1,1);
String thirdNumber = lotteryNumberString.substring(2,2);
String firstTwoWinner = firstNumber + secondNumber;
String lastTwoWinner = secondNumber + thirdNumber;
String allNumbersWinner = firstNumber + secondNumber + thirdNumber;
System.out.println("Please enter your three numbers (e.g. 123): ");
String userInput = input.next();
if(userInput.substring(0,2).equals(firstTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, the front pair matched.");
}
else if (userInput.substring(1,3).equals(lastTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, the end pair matched.");
}
else if (userInput.equals(allNumbersWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, both pairs matched.");
}
else
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Sorry, no matches. You only had one chance out of 100 to win anyway.");
}
}
}
Take a look at this article: http://www.java-made-easy.com/variable-scope.html. The problem you are facing has to do with the scope (lifetime) of the lotteryNumberString variable. It doesn't exist outside of the loop, if you declare inside the loop. To fix this, declare the lotteryNumberString before the for loop
Problem is a compilation issue.. because your lotterNumberString is scoped only inside the for loop so it is not visible outside.
You might need to do something like this.
import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String lotteryNumberString = null;
for(int i=0; i < 3; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);
lotteryNumberString = Integer.toString(lotteryNumberDigit);
}
String firstNumber = lotteryNumberString.substring(0,0);
String secondNumber = lotteryNumberString.substring(1,1);
String thirdNumber = lotteryNumberString.substring(2,2);
String firstTwoWinner = firstNumber + secondNumber;
String lastTwoWinner = secondNumber + thirdNumber;
String allNumbersWinner = firstNumber + secondNumber + thirdNumber;
System.out.println("Please enter your three numbers (e.g. 123): ");
String userInput = input.next();
if(userInput.substring(0,2).equals(firstTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, the front pair matched.");
}
else if (userInput.substring(1,3).equals(lastTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, the end pair matched.");
}
else if (userInput.equals(allNumbersWinner))
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Congratulations, both pairs matched.");
}
else
{
System.out.println("Winner: " + allNumbersWinner );
System.out.println("Sorry, no matches. You only had one chance out of 100 to win anyway.");
}
}

Issue with ending a while loop

I am trying to make the program end when total reaches 10, but for some reason my while loop continues counting when it reaches 10. I have the int percent to find the percent once 10 questions are answered.
import java.util.*;
class CAI {
private static Scanner input;
public static void main(String[] arguments) {
menu();// calls menu method
compute();// calls compute method
}
public static void menu() {// method that displays menu
System.out.println(" CAI MENU ");
System.out.println("\n)");
System.out
.println("\n1) DIFFICULTY 1\n2) DIFFICULTY 2\n3) DIFFICULTY 3\n4) DIFFICULTY 4");
}
public static int[] Blop() {
Random rand = new Random();
int arr[] = new int[8];
arr[0] = rand.nextInt(9);
arr[1] = rand.nextInt(9);
arr[2] = rand.nextInt(99);
arr[3] = rand.nextInt(99);
arr[4] = rand.nextInt(999);
arr[5] = rand.nextInt(999);
arr[6] = rand.nextInt(9999);
arr[7] = rand.nextInt(9999);
return arr;
}
public static void compute() {
int difficulty;
input = new Scanner(System.in);
System.out.println("Enter an option: ");
difficulty = input.nextInt();
int total = 0;
int percent = 0;
while (total <= 10) {
if (difficulty == 1) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[0] + " times "
+ num[1] + " ? :");
total++;
System.out.print(total);
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[0] * num[1])) {
System.out.print(Correct);
percent++;
} else {
System.out.print(Wrong);
}
} while (ans != (num[0] * num[1]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
}
if (difficulty == 2) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[2] + " times "
+ num[3] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[2] * num[3])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[2] * num[3]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 3) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[4] + " times "
+ num[5] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[4] * num[5])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[4] * num[5]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
if (difficulty == 4) {
int num[] = new int[2];
int ans;
String choice;
do {
num = Blop();
do {
System.out.print("How much is " + num[6] + " times "
+ num[7] + " ? :");
ans = input.nextInt();
String Correct;
String Wrong;
String[] correct = { "Very good! ", "Excellent! ",
"Nice work! ", "Keep up the good work! " };
String[] wrong = { "No. Please try again. ",
"Wrong. Try once more. ", "Don’t give up! ",
"No. Keep trying " };
Random rand = new Random();
Correct = correct[rand.nextInt(correct.length)];
Wrong = wrong[rand.nextInt(wrong.length)];
if (ans == (num[6] * num[7])) {
System.out.print(Correct);
} else {
System.out.print(Wrong);
}
} while (ans != (num[6] * num[7]));
System.out.print("Do you want more questions(yes/no) :");
input.nextLine();
choice = input.nextLine();
} while (choice.equalsIgnoreCase("yes"));
}
System.out.print(100 / 10 * percent);
}
}
Your while loop is declared:
"while total is less than or equal to ten"
which means it will run once again at 10.
just make it while total <10
edit: you also don't increment total anywhere.
total++;
will do it.
edit: it appears you do. sorry the code is hard to read on a phone.
There could be multiple reasons for this happening. One such reason is that if the variable difficulty does not equal one(this variable is nowhere to be found in your code also), then total will never be incremented, and as a result the first while loop will last forever. Because you have not shared all of your code, it could also be that ans != (num[0] * num[1] is never true, and as a result, the innermost do/while loop is executed forever. If you post the rest of your code, we will be able to assist you more.
EDIT: OK, thanks. It looks like your problem is due to the fact that while the user continues to get the question wrong, they cannot escape the inner while loop, therefore not being able to escape the outer while loop. The solution to that is easy, simply changing while (ans != (num[4] * num[5])); to ans != (num[0] * num[1]) && total < 10, thereby giving the code a way to escape while the user is getting the question wrong.

How to randomly position a variable within X + Y = Z operation and loop

I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".

Java Unexpected Programming Result

I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.

Guessing number using lower,higher,correct options in java

I'm trying to write a java code in java that has following output.
---JGRASP exez: java Guess
Is the number 50? H
Ia the number 75? L
Is the number 62? L
Is the number 56? L
Is the number 53? L
Is the number 51? C
It took me 6 guesses!
---JGRASP: operation complete.
As you see it always cuts range in half.I spent hours trying to figure it out without results.I would really appreciate if you could at least give a hint.Here's my unsuccessful attempt to write the code.
import java.util.Scanner;
public class GuessNumber
{
public static void main(String[]args)
{
int num1 = 0,num2 = 100,guesses = 0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Is the number " + <?> + "? "); //have no idea
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}
public static void main(String[]args)
{
Random randomNumber = new Random();
int num1 = 0,num2 = 100,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=randomNumber.nextInt(num2-num1) + num1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
Try this, what it does is that, while the answer is not correct, It will take in num1(the min value for the guess) and num2(the max value for the guess) and find their average. If the number is higher than the latest guess, we set the lower bound to the latest guess, if it's lower, we set the upper bound to the latest guess.
import java.util.Scanner;
public class GuessNumber{
public static void main(String[]args)
{
int num1 = 0,num2 = 101,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=(num1+num2) /2 > 0? (num1+num2) /2:1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guesses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}

Categories