简体   繁体   English

通过Java中的数组接受输入

[英]Accepting input through an array in Java

I'm trying to have the user enter an array of numbers(=marks of students). 我正在尝试让用户输入数字数组(=学生的分数)。 Also, the user himself will decide the size of the array, ie, the number of students in class. 同样,用户自己将决定数组的大小,即班上的学生人数。 Having accepted the marks of each student, i want to store them in an array, display the marks of all students, and compute the average of the class. 接受了每个学生的分数后,我想将它们存储在一个数组中,显示所有学生的分数,并计算班级的平均值。 Will get to the average part later. 稍后会达到平均水平。 Can someone help me with this (apparently wrong) piece of code, thank you!! 有人可以帮我解决这段(显然是错误的)代码,谢谢!

package chapter2.Arrays;
import java.util.*;

public class Arrays_ExampleOne {

static int size;
static int marks;
static int [] numbers=new int [size];
static Scanner in=new Scanner(System.in);


public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Welcome to Cincinnati Elementary");
    System.out.println("Class report details for ");
    System.out.println("Enter the number of students in the class");
    size=in.nextInt();
    System.out.println("Enter the marks of each student");
    for(int i=0;i<=size;i++)
    {
    numbers[i]=in.nextInt();    
    }

/*  System.out.println("The marks of all students are"+ " ");
    {
    for(int i=0;i<=size;i++)
    {
        System.out.print(numbers[i]);
    }
    System.out.println();

    }
    //int avg=
    */}
}

=========================================================== ================================================== =========

Revised code, looking to create a function outside of main to calculate an array's average: 修改后的代码,希望在main之外创建一个函数以计算数组的平均值:

package chapter2.Arrays;
import java.util.*;

public class Arrays_ExampleOne {

/*static int size;
static int marks;
static int [] numbers=new int [size];*/
static Scanner in=new Scanner(System.in);


    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Welcome to Cincinnati Elementary");
        System.out.println("Class report details for ");
        System.out.println("Enter the number of students in the class");
        int size;
        //static int marks;
        //static int [] numbers=new int [size];

        size=in.nextInt();

        int [] numbers=new int [size];
        System.out.println("Enter the marks of each student");
        for(int i=0;i<size;i++)
        {
        numbers[i]=in.nextInt();    
        }

        System.out.println("The marks of all students are:"+ " ");
        {
        for(int temp:numbers)
        {
            System.out.print(temp+ " ");
        }
        System.out.println();
        }

        int arraySize=numbers.length;
        int arraySum=0;
        //Calculate the sum of array elements
        for(int temp1:numbers)
        {
            arraySum+=temp1;
        }

        int average=arraySum/arraySize;

        System.out.println("The average of all the students scores is:"+ " "+average);
    }

    /*public int calculateAverage(int array[])
    {
        int arraySize=array.length;

    }*/
}

============================================================== Added separate code for calculating Average, outside of main. ================================================== =============在main之外添加了用于计算平均值的单独代码。

package chapter2.Arrays;
import java.util.*;

public class Arrays_ExampleOne {

/*static int size;
static int marks;
static int [] numbers=new int [size];*/
static Scanner in=new Scanner(System.in);


    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Arrays_ExampleOne obj=new Arrays_ExampleOne();
        System.out.println("Welcome to Cincinnati Elementary");
        System.out.println("Class report details for ");
        System.out.println("Enter the number of students in the class");
        int size;
        //static int marks;
        //static int [] numbers=new int [size];

        size=in.nextInt();

        int [] numbers=new int [size];
        System.out.println("Enter the marks of each student");
        for(int i=0;i<size;i++)
        {
        numbers[i]=in.nextInt();    
        }

        System.out.println("The marks of all students are:"+ " ");
        {
        for(int temp:numbers)
        {
            System.out.print(temp+ " ");
        }
        System.out.println();
        }

    /*  int arraySize=numbers.length;
        int arraySum=0;
        //Calculate the sum of array elements
        for(int temp1:numbers)
        {
            arraySum+=temp1;
        }

        int average=arraySum/arraySize;

        System.out.println("The average of all the students scores is:"+ " "+average);*/
        int average=obj.calculateAverage(numbers);
        System.out.println("The average of all the students is:"+ " "+average);
    }

    public int calculateAverage(int array[])
    {
        int arraySize=array.length;
        int arraySum=0;
        for(int temp: array)
        {
        arraySum+=temp;
        }

        int average=arraySum/arraySize;

        return average;
    }
}

Firstly, you should ask user to input the size first, then you set the array size: 首先,应先要求用户输入大小,然后设置数组大小:

static int size;
static int marks;
static Scanner in=new Scanner(System.in);

public static void main(String[] args) {
    System.out.println("Enter number of student:");
    size = in.nextInt();
    int [] numbers=new int [size];

    //the rest of your code goes here
}

Note: Be careful with your for loop: 注意:请注意您的for循环:

for(int i=0;i<=size;i++){
             ^
    numbers[i]=in.nextInt();
}

It will result ArrayIndexOutOfBoundException since you are trying to access the element at index size , which the max index of array with n size is n-1 . 这将导致ArrayIndexOutOfBoundException ,因为你想在索引访问元素size ,其最大indexn大小的数组为n-1。 Should be < instead of <= 应该是 <而不是<=

For method calculateAverage, it should looks like this: 对于方法calculateAverage,它应如下所示:

public static double calculateAverage(int array[])
{
    double sum=0.0;
    for(int i=0;i<array.length;i++){
       sum+=array[i];
    }
    return sum / array.length;
}

note that this method should be static since you want to use it inside static method, and average always deals with double / float datatype, not int 请注意,此方法应该是静态的,因为您想在静态方法中使用它,并且average始终处理double / float数据类型,而不是int

From main method, you can call it like this: 在main方法中,您可以这样调用它:

System.out.println("Average marks:"+calculateAverage(numbers));
static int size;
static int marks;
static int [] numbers=new int [size];

At the time the array is created, size is still at the default value, which is zero. 创建数组时, size仍为默认值零。 You always end up with an array of length zero here. 在这里,您总是以长度为零的数组结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM