如何在用户输入输入之前循环运行?

时间:2020-07-19 04:13:37

标签: java while-loop

我试图为每个输入用户输入运行while循环,但是不知道如果用户未输入输入则如何停止。 如果用户没有输入输入,我需要在while循环停止时提供帮助。

代码:

import java.util.*;

class petrol{
    public static void main(String[] args){
    int vehicle_counter=0,petrol_counter=0;
    System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
    Scanner s1 = new Scanner(System.in);
    ArrayList<Integer> array = new ArrayList<Integer>();
    
    while(true){
        if(petrol_counter<=200 && array.size()<50){
            int input = s1.nextInt();
            petrol_counter=petrol_counter+input;
            vehicle_counter++;
            array.add(input);   
        }
        else{
            System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
            break;
        }   
    }
    System.out.println("Hii");
    }
    
}

例如:如果我输入2 3 4 2并按Enter,则循环应停止。

可能的解决方案问题: 如果我使用while(s1.nextInt().equals(true)),则会收到错误消息。 如何使用break?

2 个答案:

答案 0 :(得分:0)

因此,您可以尝试类似的方法。由于您只需要单行输入,因此可以使用b来解析输入,而不要使用Scanner来解析输入。而且,BufferedReaderBufferedReader更快。

代码如下:

Scanner

答案 1 :(得分:0)

如果要保留扫描器,还可以将输入作为char并具有一个if语句,当按下某个字符时该语句将退出循环。

import java.util.*;

public class petrol {
    public static void main(String[] args) {
        int vehicle_counter = 0, petrol_counter = 0;
        System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
        Scanner s1 = new Scanner(System.in);
        ArrayList<Integer> array = new ArrayList<Integer>();

    while (true) {
        if (petrol_counter <= 200 && array.size() < 50) {
            char input = s1.next().charAt(0); // use char instead

            if (input == 'q' || input == 'Q') { //if user enters q or Q
                System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
                break;
            }

            petrol_counter = petrol_counter + input;
            vehicle_counter++;
            array.add((int) input); //Cast to int
        }
    }
    System.out.println("Hii");
}

}