英文:
JAVA: Signal start of new input with space instead of enter
问题
我有一个任务,需要创建一个程序,该程序将接受输入并将其打印到控制台。非常简单。不过有一个问题。我必须将信息存储在单独的变量中,但输入的样式如下。
输入:
Blah 123 Green
我知道我可以创建一个与单个变量关联的单个扫描器输入,将所有内容都存储为一个字符串,但是对于Blah、123和Green,都必须存储在不同的变量中。通常情况下,如果我可以使用回车键表示新输入,我会这样做:
Scanner scan = new Scanner(System.in);
String first = scan.nextLine();
int second = Integer.parseInt(scan.nextLine());
String third = scan.nextLine();
但在这种情况下,空格必须起到回车键的作用。我该如何处理?
英文:
I have an assignment to create a program that will take input and print it to the console. Pretty simple. There is one issue though. I have to store the information in separate variables but the input looks like this.
Input:
Blah 123 Green
I'm aware that I can create a single scanner input tied to a single variable that will store all of that as one String but for the assignment Blah, 123, and Green would all have to be stored in different variables. Normally what I would do if I could use the enter key to signal new input would be
Scanner scan = new Scanner(System.in);
String first = scan.nextLine();
int second = Integer.parseInt(scan.nextLine());
String third = scan.nextLine();
but in this case, the spaces have to act as the enter key instead. how would I go about this?
答案1
得分: 0
你可以使用 next()
来读取单个输入:
String first = scan.next();
int second = scan.nextInt();
String third = scan.next();
英文:
You could use next()
to read individual inputs:
String first = scan.next();
int second = scan.nextInt());
String third = scan.next();
专注分享java语言的经验与见解,让所有开发者获益!
评论