This question already has an answer here:
这个问题在这里已有答案:
- How to use java.util.Scanner to correctly read user input from System.in and act on it? 1 answer
如何使用java.util.Scanner正确读取System.in中的用户输入并对其进行操作? 1个答案
I want to be able to input:
我希望能够输入:
Avoid:
alice bob carol dave eve
and have {alice,bob,dave,eve} in the arraylist avoid
在arraylist避免使用{alice,bob,dave,eve}
package lunch;
import java.util.ArrayList;
import java.util.Scanner;
public class LetsDoLunch {
public static void main(String[] args){
String s = "";
ArrayList<String> avoid = new ArrayList<String>();
System.out.println("Avoid:");
Scanner sc2 = new Scanner(System.in);
while(true){
s = sc2.next();
if(s.equals("")){
break;}
avoid.add(s);
}
System.out.println("done");
for (int i = 0; i < avoid.size(); i++)
{
System.out.println(avoid.get(i));
}
I'm pretty sure something it's something to do with the sc2.next(); I enter the input line after Avoid: and then nothing happens even after I press enter
我很确定它与sc2.next()有关;我在避免之后进入输入行:然后在按下回车后没有任何反应
2 个解决方案
#1
0
Try this
public static void main(String[] args) {
String s = "";
ArrayList<String> avoid = new ArrayList<String>();
System.out.println("Avoid:");
Scanner sc2 = new Scanner(System.in);
Boolean flag = true;
s = sc2.nextLine();
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
avoid.add(words[i]);
}
System.out.println("done");
for (int i = 0; i < avoid.size(); i++) {
System.out.println(avoid.get(i));
}
}
#2
1
Instead of s = sc2.next() use s = sc2.nextLine()
而不是s = sc2.next()使用s = sc2.nextLine()
#1
0
Try this
public static void main(String[] args) {
String s = "";
ArrayList<String> avoid = new ArrayList<String>();
System.out.println("Avoid:");
Scanner sc2 = new Scanner(System.in);
Boolean flag = true;
s = sc2.nextLine();
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
avoid.add(words[i]);
}
System.out.println("done");
for (int i = 0; i < avoid.size(); i++) {
System.out.println(avoid.get(i));
}
}
#2
1
Instead of s = sc2.next() use s = sc2.nextLine()
而不是s = sc2.next()使用s = sc2.nextLine()