具有从Scanner存储的数字的字符串的平均值

时间:2015-11-16 17:29:35

标签: java string int java.util.scanner

我是编码的新手,并且已经完成了使用扫描仪从用户那里获得三个月平均降雨量(11月,12月,1月)的任务,然后平均了三个月的降雨量。

我显然做错了,因为我已将平均值初始化为字符串,但不知道如何初始化变量?基本上我不知道如何将降雨量的用户输入结果转换为整数,如果有人可以帮助我使用我的代码以及我如何正确平均三个月,那就太棒了,谢谢!

import java.util.Scanner;
public class rainfall {

  public static void main (String[] args) {
    Scanner stdin = new Scanner (System.in);

    String November, December, January;

    String average;

    System.out.println("what is the rainfall for November?");
    November = stdin.nextLine();

    System.out.println("what is the rainfall for December?");
    December = stdin.nextLine();

    System.out.println("what is the rainfall for January?");
    January = stdin.nextLine();

    System.out.println("the rainfall for November is: \t "  + November );
    System.out.println("the rainfall for December is: \t "  + December );
    System.out.println("the rainfall for January is: \t "  + January );

    average = November + December + January/3;
    System.out.println("The average is " + average );
  }
}

1 个答案:

答案 0 :(得分:0)

试试这可以解决您的问题

 public static void main (String[] args) {
        Scanner stdin = new Scanner (System.in);

        double November, December, January;

        double average;

        System.out.println("what is the rainfall for November?");
        November = stdin.nextDouble();

        System.out.println("what is the rainfall for December?");
        December = stdin.nextDouble();

        System.out.println("what is the rainfall for January?");
        January = stdin.nextDouble();

        System.out.println("the rainfall for November is: \t "  + November );
        System.out.println("the rainfall for December is: \t "  + December );
        System.out.println("the rainfall for January is: \t "  + January );

        average = (November + December + January)/3;
        System.out.println("The average is " + average );
      }