要求用户输入整数然后计算它们

时间:2015-12-03 22:00:51

标签: java count do-while

我需要编写一个代码,用户输入数字并添加它们,显示正数,负数,零数以及用户输入字母后输入的数字量的计数&#e e e&e #39 ;.我不确定到目前为止我所拥有的是正确的路径(它还没有编译)但这是我到目前为止所做的:

    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        int negative = 0;
        int positive = 0;
        int zeroes = 0;
        int sum = 0;
        int count = 0;
        do{
        System.out.print("Enter a float or 'e' to exit");
     int num = input.nextInt();

            if(num  < 0){
            sum += num;
            count++;
            negative++;
            }
            if (num > 0){
                sum += num;
                count++;
                positive++;
            }
            if (num == 0){
                sum += num;
                count++;
                zeroes++;

                if (num = e){
                    System.out.print(sum + count + zeroes + positive + negative);
                }

            }
    } while(true);  
    }

}

1 个答案:

答案 0 :(得分:1)

你可以这样做。请注意我试图改进的评论:

      do{
        System.out.print("Enter a float or 'e' to exit");
        String entered = input.nextLine();
        if("e".equals(entered)){
            //print stuff
            break;
        }else{
            int num;
            try {
                num = Integer.parseInt(entered);
            } catch (NumberFormatException e) {
                System.out.println("Not a number nor e");
                continue; // re-do the loop
            }
            if(num  < 0){//; ends the line, not to be used after if condition
                sum += num;
                count++;
                negative++;
            }else if (num > 0){ // num bcan be >0 only if its not <0, so use else
                sum += num;
                count++;
                positive++;
            }else{//similar to comment above
                sum += num;
                count++;
                zeroes++;
            }

        }
    } while(true);