I wrote a Java program that is supposed to take marks of two students, store them in the array, calculate their individual average marks and display it. The class name is Student. It has a function marks() that takes marks of 5 subjects input from the user and store it in the array. It works fine if I use one object to access it. the problem arises when I'm creating a second object. When I create a new object, it should create a new instance of the array, isn't it? But it's not doing so I suppose. It works for other data type values like a String, or int, etc. The code is as follows:
import java.util.Scanner;
public class A3_student_marks {
public static void main(String[] args) {
Student s1 = new Student();
System.out.println("Enter marks of student 1:");
s1.marks();
Student s2 = new Student();
System.out.println("Enter marks of student 2:");
s2.marks();
s1.display();
s2.display();
}
}
class Student
{
private int[] m;
int avg = 0;
public Student()
{
this.m = new int[5];
}
public void marks()
{
Scanner sc = new Scanner(System.in);
try{
for(int i=0;i<5;i++)
{
System.out.print("Enter marks of subject "+(i+1)+": ");
m[i] = sc.nextInt();
avg += m[i];
}
avg /= 5;
}
finally
{
sc.close();
}
}
public void display()
{
System.out.println("Average marks: "+avg);
}
}
It takes the input for the first time when called using first object. But as soon as the call using second object starts, it displays the following exceptions:
Enter marks of student 1:
Enter marks of subject 1: 1
Enter marks of subject 2: 2
Enter marks of subject 3: 3
Enter marks of subject 4: 4
Enter marks of subject 5: 5
Enter marks of student 2:
Enter marks of subject 1: Exception in thread "main" java.util.NoSuchElementException
at java. Base/java.util.Scanner.throwFor(Scanner.java:945)
at java. Base/java.util.Scanner.next(Scanner.java:1602)
at java. Base/java.util.Scanner.nextInt(Scanner.java:2267)
at java. Base/java.util.Scanner.nextInt(Scanner.java:2221)
at Student.marks(A3_student_marks.java:35)
at A3_student_marks.main(A3_student_marks.java:11)
Please help me out. I can't seem to understand what's happening. Initially I declared the array without any access specifier. Then I added the 'private' access specifier. It's still the same.
Please help me out. I can't seem to understand what's happening. Initially I declared the array without any access specifier. Then I added the 'private' access specifier. It's still the same. I just wan't to know why isn't it working. P.S. I know you can calculate the average without an array here, but I just wanna know what is wrong here