import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
为什么程序运行其他而不是要求我输入?
答案 0 :(得分:4)
您应该使用scanner.nextLine()
:
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();
答案 1 :(得分:2)
您只是创建了一个扫描仪,但没有告诉它从标准输入中读取内容。您可以通过致电scanner.next()
来阅读令牌scanner.nextLine()
来阅读一条线等,然后在if语句中将Scanner
与String
进行比较
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}
答案 2 :(得分:1)
您只创建了Scanner对象的实例。您需要调用Scanner#nextLine()
之类的方法来读取输入,然后将读取的值与“我”或“我”进行比较。
示例:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
您也可以使用String#equalsIgnoreCase
进行不区分大小写的匹配。