开发者

Java - how to take undetermined amount of input from user

开发者 https://www.devze.com 2023-01-25 06:15 出处:网络
Java Question: I want to take an undetermined number of lines of input from a user. For instance, I want the user to continue entering names of people as strings until the user has no other names to

Java Question:

I want to take an undetermined number of lines of input from a user. For instance, I want the user to continue entering names of people as strings until the user has no other names to enter. I want a user-friendly way to easily indicate that the user has no more input. The loop may look like the following. Any good ideas? Any tips on improving the snippet of code is appreciated as well.

 BufferedReader read = new BufferedReader(new InputStreamReader(System.in));     

 while( <user still has more input> ) {
      System.out.println("Enter n开发者_JS百科ame: ");
      String s = read.readLine();
      ...
      <do something with s>;
      ...
 }

thank you!


You need a value that isn't a name but indicates no more data. An empty line would be good. You also want to query if they really want to quit, so in case they accidentally hit return they haven't lost all their data.

name = read.readLine(); 
Pattern p = Pattern.compile("^\\s$"); //empty line or one of just space chareacters
if (p.matcher(name).matches()) {
       System.out.println("Are you done?[y/n]");
       if (Pattern.matches("[yY]", read.readLine()) {
          //quit your loop
       }
}


You could have a boolean variable, such as finished, and check if the user enters 'Q' or another item to indicate that they are finished. If so, set finished to true and you will exit your loop on the next iteration.

Here is a quick example,

boolean finished = false;
String name = null;  // initialized to a default value.

System.out.println("Enter 'Q' to quit");
while(!finished) {
System.out.println("Enter name: ");
name = read.readLine();  // moved declaration outside of loop
if(name.equals("Q")) { 
   finished = true;
 }
  // do work with name
}

I have also modified your code a bit,

  • I have added a message to the user to indicate what terminates the input.
  • I have renamed your variable s to something more meaningful, because you are storing the user's name it seemed reasonable to change it to name.
  • As a force of habit, I have also initialized my variables with default values, so I assigned the name variable to null. Not totally necessary, but I consider it good practice.
  • Since I have assigned name a default value, I have moved it outside of your loop.


A simple way is to have users enter an empty line when they are done. You'd just check if line.equals("") or maybe trim it before.

0

精彩评论

暂无评论...
验证码 换一张
取 消