下面的代码在运行时效果很好,但是,如果您在“ bands”(带)问题中输入两个单词,您只会得到一个打印回去。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.next();
System.out.println("I like >>" + bands + "<<too!");
}
}
答案 0 :(得分:0)
类Scanner中的方法next()
将仅返回下一个标记。
如oracle文档中所述:
查找并返回此扫描仪的下一个完整令牌。一种 完整令牌的前面和后面都有与 定界符模式。等待输入到该方法时可能会阻塞 扫描,即使先前对hasNext()的调用返回true。
默认定界符带有一个空格,因此,如果您的乐队名称包含多个单词,则该单词将无效。
用于读取整行输入用户nextLine()
如果您想同时拥有两个乐队名称,请致电nextLine()
两次以分别获取每个输入:
System.out.println("What are your favorite two bands?");
String band1 = scan.nextLine();
String band2 = scan.nextLine();
System.out.println("I like >>" + band1 + " and " + band2 + "<<too!");
在这种情况下,用户必须在每次输入后按“输入”。
编辑:
如Elliott Frisch的评论中所述,其他readXXX方法不会从输入流中删除行尾。 看到: stackoverflow.com/q/13102045/2970947
您可以为每个输入使用nextLine()或在每次读取后删除行尾。带有您的代码的示例:
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
scan.nextLine();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
scan.nextLine();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.nextLine();
System.out.println("I like >>" + bands + "<<too!");
API参考:
答案 1 :(得分:0)
要获取包含多个单词的完整字符串(按enter
之前),您应该使用scan.nextLine()
而不是scan.next()
(scan.next()
仅用于读取下一个单词)。
请不要忘记在scan.nextInt()scan.nextLine()
scan.nextLine()`之后添加额外的and before
(请参见Java Scanner class reading strings):
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("What is your name? ");
String name = scan.nextLine();
System.out.println("Hello " + name);
System.out.print("What is your age? ");
int years = scan.nextInt();
int ageInMonths = years * 12;
System.out.println("Your age is " + ageInMonths + " in months");
System.out.print("What are your favorite two bands? ");
scan.nextLine(); // extra one after scan.nextInt() - it retrieves a empty string
String bands = scan.nextLine();
System.out.println("I like >>" + bands + "<< too!");
}
}
演示,控制台输出:
What is your name? John Doe
Hello John Doe
What is your age? 666
Your age is 7992 in months
What are your favorite two bands? one two three
I like >>one two three<< too!