Java stops reading after empty line

I am engaged in a school exercise and I cannot figure out how to do this. For what I read, the scanner is not the best way, but since the teacher uses only the scanner, this must be done using the scanner.

This is problem. The user will enter the text into the array. This array can reach 10 lines, and user inputs end with an empty line.

I have 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 does not work properly, and I cannot figure it out. Ideally, if the user enters:

This is line one
This is line two

and now press enter to print 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?

+5
source share
2 answers
 while (!sc.nextLine().equals("")){
        text[i] = sc.nextLine();
        i++;        
 }

: , , , . , String :

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

readline, :

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++;        
}
+1

All Articles