I have to make a loop taking a users input until “done” is entered

前端 未结 4 1215
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 01:53

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.

4条回答
  •  伪装坚强ぢ
    2020-12-20 02:16

    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 al = new ArrayList();    // 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.
      }
    }
    

提交回复
热议问题