Java stop reading after empty line

前端 未结 3 1893
你的背包
你的背包 2020-12-11 06:58

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

3条回答
  •  青春惊慌失措
    2020-12-11 07:42

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

提交回复
热议问题