问题
package harry;
import java.util.Scanner;
public class harry {
public static void main(String[] args) {
String Harr = ("Harry");
Scanner name = new Scanner(System.in);
System.out.println("Enter your name");
name.nextLine();
if(name.equals("Harry")) {
System.out.println("She hates you");
} else if (name.equals("Nick")) {
System.out.println("She loves you");
}
}
}
In this code, I am trying to write the following:
- If the name is “Harry”, it should print “She hates you”
- If the name is “Nick”, it should print “she loves you”
However, when I write either one of these names, it doesn’t print anything.
回答1:
Scanner is used a little differently :
package harry;
import java.util.Scanner;
public class harry {
public static void main(String[] args) {
String Harr = ("Harry");
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
String name = input.nextLine();
if(name.equals("Harry")) {
System.out.println("She hates you");
} else if (name.equals("Nick")) {
System.out.println("She loves you");
}
}
}
回答2:
Try this Nick Nicholas it works when I try:
import java.util.Scanner;
public class harry {
public static void main(String[] args) {
String Harr = ("Harry");
String s;
Scanner name = new Scanner(System.in);
System.out.println("Enter your name");
s = name.nextLine();
if(s.equals("Harry")) {
System.out.println("She hates you");
} else if (s.equals("Nick")) {
System.out.println("She loves you");
}
}
}
回答3:
Assign the value of name.nextline to a string and then do the conditional check
The code will be like:
String n= name.nextLine();
if(n.equals("Harry")) {
System.out.println("She hates you");
} else if (n.equals("Nick")) {
System.out.println("She loves you");
}
来源:https://stackoverflow.com/questions/29255542/scanner-equals-returns-false-in-either-case