Java stop reading after empty line

前端 未结 3 1895
你的背包
你的背包 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条回答
  •  猫巷女王i
    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;
    }
    

提交回复
热议问题