调用方法添加输入

时间:2013-02-28 14:31:17

标签: java methods

我正在编写一个程序,用户输入10个数字,并在输入时将它们加在一起,然后显示平均值。到目前为止,我已经拥有了这个,并且我仍然坚持要在循环体中放置什么来实现这一目标。谢谢!

import java.util.Scanner;

public class InputMethod
{
public static void main(String[] args)
{
    int loop_Value;
    int end_Value = 10;
    for(loop_Value =0; loop_Value < end_Value; loop_Value++)
    {
        readInteger();

    }
}

private static int readInteger()
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter an integer");
    while (!scan.hasNextInt()) 
    {
        scan.next();
        System.out.println ("Bad input. Enter an integer");
    }
    int input = scan.nextInt();
    {
        return input;
    }

}

}

3 个答案:

答案 0 :(得分:2)

添加整数值sum。在循环体中放

sum += readInteger();

最后

System.out.println("The sum is " + sum);

然后因为数字的数量是固定的。

System.out.println("The average is " + (sum / end_Value));

答案 1 :(得分:1)

您只阅读了输入:它缺少 readInteger

返回的单个数字的记忆

这是一个工作代码恐怖风格的,不符合Oracle / Sun指南。

public class InputMethod {

    List<Integer> numbers = new ArrayList<Integer>();

    public static void main(String[] args) {

        int endValue = 10;

        InputMethod inputMethod = new InputMethod();
        for (int loop_Value = 0; loop_Value < endValue; loop_Value++) {
            int number=inputMethod.readInteger();/*storage the input*/

            inputMethod.numbers.add(number);
        }
        int sum=0;
        for (int loop_Value = 0; loop_Value < inputMethod.numbers.size(); loop_Value++) {
            sum=sum+inputMethod.numbers.get(loop_Value); /*partial sum*/
        }

        System.out.println("Sum of "+inputMethod.numbers+"= "+sum);
        System.out.println("Average of "+inputMethod.numbers+"= "+(double)(sum/inputMethod.numbers.size()));

    }

    private int readInteger() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter an integer");
        while (!scan.hasNextInt()) {
            scan.next();
            System.out.println("Bad input. Enter an integer");
        }
        int input = scan.nextInt();
        {

            return input;
        }

    }

}

一些观察:

  • 变量的名称没有 _ ;只有当名字不明白时才能插入他;
  • 最好不要在循环之外声明 for 循环的变量:每个变量都必须将mininum范围纳入程序;
  • System.out.println(“输入错误。输入一个整数”); 应该是 System.err.println(“错误输入。输入一个整数”); :正常消息的sysout,错误的syserr。

通过学习语言来了解和应用正确的惯例会更好;之后更难。

答案 2 :(得分:0)

    int sum=0;
    for(loop_Value =0; loop_Value < end_Value; loop_Value++)
    {
      sum += (readInteger());
    }
    double avg = sum/end_value;