开发者

Java stop reading after empty line

开发者 https://www.devze.com 2023-04-10 16:54 出处:网络
I\'m doing an school exercise and I can\'t figure how to do one thing. For what I\'ve read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.

I'm doing an school exercise and I can't figure how to do one thing. For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.

This is the problem. The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.

I've done this:

 String[] text = new String[11]
 Scanner sc = new Scanner(System.in);
 int i = 0;
 System.out.println("Please insert text:");
 while (!sc.nextLine().equals("")){
        text[i] = sc.nextLine();
        i++;        
    }

But this is not working properly and I can't figure it out. I开发者_JAVA百科deally, if the user enters:

This is line one
This is line two

and now press enter, wen printing the array it should give:

[This is line one, This is line two, null,null,null,null,null,null,null,null,null]

Can you help me?


 while (!sc.nextLine().equals("")){
        text[i] = sc.nextLine();
        i++;        
 }

This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:

while(true) {
    String nextLine = sc.nextLine();
    if ( nextLine.equals("") ) {
       break;
    }
    text[i] = nextLine;
    i++;
}


Here's the typical readline idiom, applied to your code:

String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
    text[i] = line;
    i++;        
}


The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.

String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input. 
    System.out.println("Please insert text:");
    string s = sc.nextLine();
    if (s.equals("")) break; //if input is a empty line, stop it
    text[i] = s;
}
0

精彩评论

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

关注公众号