简体   繁体   中英

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! 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. 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); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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