简体   繁体   English

这个方法有什么问题...?

[英]What's wrong with this method...?

import java.util.Scanner;

public class InputCalculator {
    public static void inputThenPrintSumAndAverage(){
        Scanner scanner = new Scanner(System.in);

        boolean first = true;

        int sum = 0;
        int count = 0;
        int avg = 0;
        while(true){
            int number = scanner.nextInt();
            boolean isAnInt = scanner.hasNextInt();

            if(isAnInt){
                sum += number;
                count++;
                avg = Math.round((sum)/count);
            }else{
                System.out.println("SUM = " + sum + " AVG = " + avg);
                break;
            }
            scanner.nextLine();
        }
        scanner.close();
    }
}

When input is "1, 2, 3, 4, 5, a", I think it's not reading the input 5, resulting sum = 10 and avg = 2!当输入为“1,2,3,4,5,a”时,我认为它没有读取输入 5,结果 sum = 10 和 avg = 2! Why it's happening?为什么会发生? By the way it's just a method not whole code!顺便说一句,它只是一个方法而不是整个代码!

When scanner.nextInt() provides you '5', the next line 'scanner.hasNextInt() is false.当scanner.nextInt() 为您提供'5' 时,下一行'scanner.hasNextInt() 为false。 Just change line order只需更改行顺序

import java.util.Scanner;

public class InputCalculator {
    public static void inputThenPrintSumAndAverage(){
        Scanner scanner = new Scanner(System.in);

        boolean first = true;

        int sum = 0;
        int count = 0;
        int avg = 0;

        while(true){
            boolean isAnInt = scanner.hasNextInt();

            if(isAnInt){
                int number = scanner.nextInt();
                sum += number;
                count++;
                avg = Math.round((sum)/count);
            }else{
                System.out.println("SUM = " + sum + " AVG = " + avg);
                break;
            }
            scanner.nextLine();
        }
        scanner.close();
    }
}

you can also clean the code like你也可以像清理代码一样

import java.util.Scanner;

public class InputCalculator {
    public static void inputThenPrintSumAndAverage(){
        Scanner scanner = new Scanner(System.in);

        int sum = 0;
        int count = 0;

        while( scanner.hasNextInt() ){
            int number = scanner.nextInt();
            sum += number;
            count++;
        }
        
        scanner.close();

        double avg = Math.round((sum)/count);
        System.out.println("SUM = " + sum + " AVG = " + avg); 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM