calculate average with user input

◇◆丶佛笑我妖孽 提交于 2019-12-11 16:25:24

问题


I'm writing a program to calculate average with user input.

import java.util.Scanner;
public class mean
{   
    static Scanner input = new Scanner (System.in);
    public static void main (String[] args)
    {
    double i;
    double sum = 0;
    int count = 0;
    do
    {
        System.out.println("input");
        i = input.nextDouble();
        sum = sum + i;
        count++;
    }while (i != 0);
    System.out.println("sum is " + sum + " count is " + (count - 1));
    System.out.println("average is " + sum / (count - 1));
}
}

here if I input 0, it will calculate. but if there is 0s in the list. can somebody guide me a great while condition?


回答1:


You could ask the scanner whether or not the next token that the scanner is reading is a double and break if it isn't. Example below:

import java.util.Scanner;
public class mean
{   
    static Scanner input = new Scanner (System.in);
    public static void main (String[] args)
    {
    double i;
    double sum = 0;
    int count = 0;
    while(input.hasNextDouble())
    {
        System.out.println("input");
        i = input.nextDouble();
        sum = sum + i;
        count++;
    }
    System.out.println("sum is " + sum + " count is " + (count));
    System.out.println("average is " + sum / (count));
}
}

If the user inputs a non-digit character (e.g. not '+', '-', 0-9, '.', etc.), the loop will break because input.hasNextDouble() will return false.




回答2:


instead of sum = sum + i an easier way would be sum += i



来源:https://stackoverflow.com/questions/10887498/calculate-average-with-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!