my program first shows two options a开发者_JAVA技巧nd asks the user to choose one choice the problem is my program ignores the input of the scanner and doesn't enter the block even if the condition is true so what the problem i !!!
import java.util.Scanner;
public class TestS {
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
String s;
System.out.println("Choose an operation to apply :\n1.Een\n2.De");
s=kb.nextLine();
System.out.println(s);
if(s=="1")
{
System.out.print(5454545);
}
else if(s=="2")
{
System.out.print(2);
}
}
}
You should never compare strings using ==
. Use the .equals
method (or sometimes the .equalsIgnoreCase
method):
if(s.equals("1"))
// ...
Since you're using a scanner and you seem to require numbers as input, there is a better way though:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Choose an operation to apply :\n1.Een\n2.De");
while (!kb.hasNextInt())
System.out.println(kb.next() + " is not a number. Try again...");
int choice = kb.nextInt();
System.out.println(choice);
switch (choice) {
case 1: System.out.print(5454545); break;
case 2: System.out.print(2); break;
default: System.out.println("Invalid choice."); break;
}
}
}
The problem is the equals operator. Remember that == compare memory references and not object values. We know that String have a String pool, but in this case it's not used.
try to use .equals() instead ==
change you if
if(s == null ? "1" == null : s.equals("1"))
{
System.out.print(5454545);
}
精彩评论