我必须创建一个循环来获取用户输入,直到输入“完成”

时间:2013-12-14 22:50:59

标签: java string loops arraylist

我正在尝试制作一个ArrayList,其中包含用户输入的多个名称,直到插入单词done,但我不确定如何。如何实现?

4 个答案:

答案 0 :(得分:1)

    ArrayList<String> list = new ArrayList<String>();
    String input = null;
    while (!"done".equals(input)) {
        //  prompt the user to enter an input
        System.out.print("Enter input: ");

        //  open up standard input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


        //  read the input from the command-line; need to use try/catch with the
        //  readLine() method
        try {
            input = br.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read input!");
            System.exit(1);
        }
        if (!"done".equals(input) && !"".equals(input))
            list.add(input);
    }
    System.out.println("list = " + list);

答案 1 :(得分:0)

我可能会这样做 -

public static void main(String[] args) {
  System.out.println("Please enter names seperated by newline, or done to stop");
  Scanner scanner = new Scanner(System.in);     // Use a Scanner.
  List<String> al = new ArrayList<String>();    // The list of names (String(s)).
  String word;                                  // The current line.
  while (scanner.hasNextLine()) {               // make sure there is a line.
    word = scanner.nextLine();                  // get the line.
    if (word != null) {                         // make sure it isn't null.
      word = word.trim();                       // trim it.
      if (word.equalsIgnoreCase("done")) {      // check for done.
        break;                                  // End on "done".
      }
      al.add(word);                             // Add the line to the list.
    } else {
      break;                                    // End on null.
    }
  }
  System.out.println("The list contains - ");   // Print the list.
  for (String str : al) {                       // line
    System.out.println(str);                    // by line.
  }
}

答案 2 :(得分:-1)

String[] inputArray = new String[0];
do{
  String input=getinput();//replace with custom input code
  newInputArray=new String[inputArray.length+1];
  for(int i=0; i<inputArray.length; i++){
    newInputArray[i]=inputArray[i];
  }
  newInputArray[inputArray.length]=input
  intputArray=newInputArray;
}while(!input.equals("done"));

未经测试的代码,带上一粒盐。

答案 3 :(得分:-2)

ArrayList<String> names = new ArrayList<String>();
String userInput;
Scanner scanner = new Scanner(System.in);
while (true) {
    userInput = scanner.next();
    if (userInput.equals("done")) {
        break;
    } else {
        names.add(userInput);
    }
}       
scanner.close();