Java stop reading after empty line

前端 未结 3 1889
你的背包
你的背包 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++;
    }
    
    0 讨论(0)
  • 2020-12-11 07:42

    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 讨论(0)
  • 2020-12-11 07:44

    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++;        
    }
    
    0 讨论(0)
提交回复
热议问题