Why won't this code loop?
Hello everyone, I'm brand new to java and also to this forum. Hoping to get some help and maybe help others when I get better at this.
Ok, so I tried to make a loop, if you enter "y" the code is supposed to loop, otherwise the program should terminate, but for some reason it won't loop, and I can't figure out what I'm doing wrong...
Code :
import java.util.Scanner;
public class scanner {
public static void main (String args[]){
Scanner scn = new Scanner(System.in);
Scanner go = new Scanner(System.in);
int fnum, snum, answer;
String yn = "y";
while(yn == "y"){ // this is there my loop starts
System.out.print("enter first number: ");
fnum = scn.nextInt();
System.out.print("enter second number: ");
snum = scn.nextInt();
answer = fnum - snum;
System.out.println(fnum + " - " + snum + " = " + answer);
System.out.print("go again (y/n)? ");
yn = go.nextLine();
System.out.print(yn); // just so make sure yn="y"
}
}
}
Re: Why won't this code loop?
Use the equals method to compare Strings, not the == operator.
Re: Why won't this code loop?
If i do that, i get a "Type mismatch: cannot convert from Strings to boolean"...
Re: Why won't this code loop?
Please post the code that created the error message.
Re: Why won't this code loop?
It is this one, here without the ==.
The error message reads:
Quote:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to boolean
at scanner.main(scanner.java:12)
Code :
import java.util.Scanner;
public class scanner {
public static void main (String args[]){
Scanner scn = new Scanner(System.in);
Scanner go = new Scanner(System.in);
int fnum, snum, answer;
String yn = "y";
while(yn = "y"){ // this is there my loop starts
System.out.print("enter first number: ");
fnum = scn.nextInt();
System.out.print("enter second number: ");
snum = scn.nextInt();
answer = fnum - snum;
System.out.println(fnum + " - " + snum + " = " + answer);
System.out.print("go again (y/n)? ");
yn = go.nextLine();
System.out.print(yn); // just so make sure yn="y"
}
}
}
Re: Why won't this code loop?
Code :
while(yn = "y"){ // this is there my loop starts
The while statement requires a boolean value inside of the ().
Your code has an assignment statement inside of the ()s that evaluates to a String.
Quote:
cannot convert from String to boolean
The compiler is complaining that there is no way to convert the String to the required boolean
Where are you using the equals() method that I recommended?