I have to make a loop taking a users input until “

2020-02-13 02:21发布

I'm trying to make an ArrayList that takes in multiple names that the user enters, until the word done is inserted but I'm not really sure how. How to achieve that?

4条回答
爷的心禁止访问
2楼-- · 2020-02-13 02:25
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();
查看更多
乱世女痞
3楼-- · 2020-02-13 02:42
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"));

untested code, take it with a grain of salt.

查看更多
淡お忘
4楼-- · 2020-02-13 02:43
    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);
查看更多
虎瘦雄心在
5楼-- · 2020-02-13 02:44

I would probably do it like this -

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.
  }
}
查看更多
登录 后发表回答