Scanner Issues: Read for more detail, thanks.
Code Java:
while(a < amount){
int num1 = 2 + (int)(Math.random()*23);
int num2 = 2 + (int)(Math.random()*23);
int num3 = 2 + (int)(Math.random()*23);
int num4 = 2 + (int)(Math.random()*23);
String answer = null;
if(num1*num4 > num2*num3){
answer = ""+num1+"/"+num2+"";
}
else if(num1*num4 < num2*num3){
answer = ""+num3+"/"+num4+"";
}
System.out.println("The larger of " + num1 + "/" + num2 + " or " + num3 + "/" + num4 + " is");
String reply = scan.next();
if(reply == answer){
System.out.println("Correct!");
correct++;
score += 5;
}
else{
System.out.println("Wrong!");
wrong++;
score -= 9;
}
amount--;
}
This piece of my code determines whether a fraction is greater than another using cross multiplying. The user must decide which fraction is the larger value. In order to place "/" into the answer, I converted the "reply" and "answer" variables into Strings. However, the output comes out like so:
---------------------------------
The larger of 4/3 and 10/3 is
10/3
Wrong!
---------------------------------
I even tried adding - "System.out.println(answer); - and placed that exact answer into the line. But my answer was still wrong. Can anyone help me understand some more about Scanners, and how they work? I'm not quite sure why the program keeps returning "Wrong!" to me when I am clearly putting in the correct answer. Thanks in advance!
Re: Scanner Issues: Read for more detail, thanks.
I solved the issue by changing the "==" to .equals().
Re: Scanner Issues: Read for more detail, thanks.
Concatenating the empty Strings is an abuse of your powers.
Re: Scanner Issues: Read for more detail, thanks.
Quote:
Originally Posted by
Staticity
I solved the issue by changing the "==" to .equals().
This is a common error :)