Reputation: 11
import java.util.Scanner;
public class Mal {
public static void main(String[] args) {
System.out.println("Welcome");
Scanner myinput = new Scanner(System. in );
System.out.println("Make your choise. \n 1.Check a card number \n 2.Quit.");
int choise = myinput.nextInt();
switch (choise) {
case 1:
System.out.println("Enter your credit card number: ");
break;
case 2:
System.out.println("Are you sure?");
String answer = myinput.next();
if (answer == "yes") {
System.out.println("Byee ");
} else {
break;
}
default:
System.out.println("Idiot!");
break;
}
}
How can i get String answer for Clavier ?
Upvotes: 0
Views: 125
Reputation: 27
I can you want to read string values from the console. For that You may use BufferedReader. Following is the syntax of it:
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));
str = br.readLine(); // String str;
You need to import BufferedReader and InputStreamReader by using:
import java.io.*;
package!
Upvotes: 0
Reputation: 46395
String comparison should be made using .equals( ) method and not with the == operator.
The ==
operator compares two object references to see whether they refer to the same instance. The equals( )
method compares the characters inside a String object.
i.e
<object ref> == <object ref>
- returns a boolean that evaluates if the references point to the same object in memory.
<object ref>.equals(<object ref>)
- returns the value of the equals() method of that object. If theequals()
method does not exist, then the equals method of the "Object" class is called.
You code should be,
if (answer.equals("yes")) {
System.out.println("Byee ");
} else {
break;
}
Upvotes: 0
Reputation: 10254
You want to use the equals method instead of the == operator. The reason is that the == operator does reference comparison and the equals method checks to see if the two String values are the same.
Here is the updated code you should try:
if (answer.equals("yes")) {
System.out.println("Byee ");
} else {
break;
}
Upvotes: 2
Reputation: 81684
Dunno what "Clavier" means here, but this is wrong:
answer == "yes"
You have to compare Strings using the equals method:
answer.equals("yes")
or it won't work.
Upvotes: 0