Java-根据用户输入创建数组 [英] Java - Creating an array from user input

查看:129
本文介绍了Java-根据用户输入创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是赋值:



  1. 创建一个数组来存储10个数字。

  2. 使用循环,提示用户输入10个成绩并将其存储在数组中。

  3. 然后进行另一个循环,该循环将数组中的数字向后打印出来,并累加数组中的数字。

  4. 使用总和来计算数字的平均值。打印出数字的平均值。

  1. Create an array to store 10 numbers.
  2. Using a loop, prompt the user to enter 10 grades and store them in the array.
  3. Then make another loop that prints the numbers in the array out backwards and adds up the numbers in the array.
  4. Use the sum to calculate the average of the numbers. Print out the average of the numbers.


到目前为止我的代码:

public static void ar() {

    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);

    for(int i=0; i < grades.length; i++)
        grades[i]=kb.nextDouble();

    double sum=0;

    for(int j=10; j > grades.length; j--)
        sum=sum+grades[j];

    double ave = sum/10;

    System.out.println(ave);
}

但是它只能打印0.0十次。

However it only prints 0.0 ten times.

推荐答案

此处是带注释的解决方案,指示从初始代码更改的内容。您肯定在正确的轨道上,只是一些小问题。

Here is an annotated solution indicating what was changed from your initial code. You were definitely on the right track, just a few small issues.

public static void ar() {

    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);

    for(int i=0; i < grades.length; i++)
        grades[i]=kb.nextDouble();

    double sum=0;

    for(int j=9; j >= 0; j--) //Note here that we've changed our condition. It was running zero times before. Additionally it now runs from 9-0, since the last index is 9
        sum=sum+grades[j];

    //Look out for Integer Arithmetic!
    double ave = sum/10.0;

    System.out.println(ave);
}

这篇关于Java-根据用户输入创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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