用用户输入计算平均值 [英] calculate average with user input

查看:139
本文介绍了用用户输入计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来计算用户输入的平均值.

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

在这里,如果我输入0,它将进行计算.但是如果列表中有0.有人可以指导我好一阵子吗?

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

推荐答案

您可以询问扫描程序,该扫描程序正在读取的下一个令牌是否为double,如果不是,则中断.下面的示例:

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

如果用户输入非数字字符(例如,非'+','-',0-9,'.'等),则循环将中断,因为input.hasNextDouble()将返回false.

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

这篇关于用用户输入计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆