Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stop reading after empty line

Tags:

java

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. Ideally, 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?

like image 416
Favolas Avatar asked Oct 05 '11 15:10

Favolas


2 Answers

 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++;
}
like image 147
Mark Peters Avatar answered Nov 02 '22 23:11

Mark Peters


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++;        
}
like image 25
Matt Ball Avatar answered Nov 02 '22 23:11

Matt Ball