I am writing a code (a beginners code, i set myself targets for a simple program, and along the way i pick up all the extra details about java) and i want to be able to ask the user a yes or no answer and test that in a condition. Here is what i wrote (narrowed down to just the necessary code);
This compiles perfectly well, but when i enter the y or n (or anything for that matter) it just passes to the else statement. Always. So i tried using char and all its ways, that didnt compile right. Then using int, which compiled, but--Code:import java.util.Scanner;
class choice {
public static void main(String[] args) {
System.out.println("(y/n):");
Scanner scan = new Scanner(System.in);
String ch = scan.nextLine();
if (ch=="y") { System.out.println("you chose yes (y)"); }
else if (ch=="n") { System.out.println("you chose no (n)"); }
else { System.out.println("you didn't choose yes or no!"); }
}
}
This compiles correctly but throws up an exception (see below) when either n or y is selected:Code:import java.util.Scanner;
class choice {
public static void main(String[] args) {
System.out.println("(y/n):");
Scanner scan = new Scanner(System.in);
int ch = scan.nextInt();
if (ch=='y') { System.out.println("you chose yes (y)"); }
else if (ch=='n') { System.out.println("you chose no (n)"); }
else { System.out.println("you didn't choose yes or no"); }
}
}
am i comparing strings or characters incorrectly? (im using jdk on linux btw)Code:james@james-laptop:~/Desktop/coding/Jcoding/examples$ java choice
(y/n):
y
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at choice.main(choice.java:7)
Thanks in advance.

