当输入为空时如何中断程序

时间:2016-05-22 21:36:11

标签: java input

我有一个函数,例如,逐行读取数字,并计算这些数字的总和。 用户输入数字,每行输入一个数字,当输入'null'时,程序会中断并给出结果。 例如:

int *a[4] = { (int[]){ 1}, (int[]){ -4, -5}, (int[]){ -4, -5, 0}, (int[]){ 1, 3, 4, 6} }; for (i = 0; i < 4; i++) len = sizeof(a[i])/sizeof(int); >>8 >>5 >>4 >>

如果输入为空并且给出结果,程序如何中断?

2 个答案:

答案 0 :(得分:1)

这是我想到的使用扫描仪的代码。代码中的注释是我认为您可能搞砸的地方,关键区域和您提出的问题。

public static void sumInputs(){
    Scanner data=new Scanner(System.in);
    ArrayList <Double> allNumbers=new ArrayList<>();
    while(true){
        System.out.print("Number:");
        try{
            //IMPORTANT: Notice I use "nextLine" and not "next", because next will wait till user inputs something not null
            //and ignours the "enter" key pressed, while "nextLine" executes when the user presses the key "enter" regardless
            //of whether there is input.
            //I would imagine this is your problem
            String number=data.nextLine();

            //The part you are looking for
            //Right here is the part you are looking for
            if(!number.isEmpty()){
                //what to do if it is not null (store the numbers
                //in an ArrayList).
                allNumbers.add(Double.parseDouble(number));
            }else{
                //add up all the numbers if it is null
                double sum = 0;
                for( double i : allNumbers) {
                    sum += i;
                }
                System.out.println("The result is "+ sum);
                System.exit(0);
            }
        }catch(InputMismatchException e){
            System.out.println("Not number");
        }
    }
}

答案 1 :(得分:0)

string mystr;
    getline(cin,mystr);
    if(mystr.empty())
//do stuff
    else 
 //do stuff

我很抱歉我认为这是一个c ++问题,当我看到&gt;&gt;无论如何这里是java版本

Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        if(text.isEmpty())
            //do stuff
        else 
            //do stuff