Я пытаюсь ввести пользователя в массив чисел (= отметки студентов). Кроме того, сам пользователь будет определять размер массива, то есть количество студентов в классе. Приняв метки каждого ученика, я хочу сохранить их в массиве, отобразить метки всех учеников и вычислить среднее значение класса. Попасть в среднюю часть позже. Может кто-нибудь помочь мне с этим (видимо, неправильным) фрагментом кода, спасибо!Прием ввода через массив в Java
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=
*/}
}
=========================================== ================
Пересмотренный код, глядя создать функцию вне основной для расчета среднего Массив по:
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;
}*/
}
====== ================================================== ====== Добавлен отдельный код для расчета среднего значения, за пределами основного.
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;
}
}
Ваш код выглядит нормально, вам просто нужно сначала объявить массив 'numbers' (' int [] numbers = new int [size] ') –
Большое вам спасибо @Johannes H. –