Jump to content

Please help me to display the inputted data in array

Go to solution Solved by Vectorspace,

Your mistake is that you have a single Exam array that you are loading the scores into. Which means if you have two students, you fill the array with student 1's scores, then overwrite it with student 2's scores.

 

You need multiple scores arrays, one per student.

 

You can do this two ways:

 

#1: a 2-dimensional array. E.g.

int scores = new int[a][b]

when you access this array, e.g. scores[a] = 5 then a is the index for the student and b is the index for the score.

 

#2: Create a "Student" object, that contains a scores array. Then in your main function create an array of Student objects.  This is what Slottr recommended

This is more complicated than option 1 but is the more correct approach. Better learning experience too.

 

Good Day Everyone, I'm a first year student currently learning arrays using java. I  created a program in which the user enters the id number and the test score, then it should compute its average and display the id number, test scores and average. The problem in my program which I can't display all the scores and average but it can display the inputted id number.

Sorry for my bad english. 

import java.util.*;

public class arrayactivity1
{

	static Scanner console = new Scanner(System.in);
	public static void main(String[] args)
	{
		
		int NumberofStudent = 0;
		int NumberofExam = 0;
		
		int k = 0;
		System.out.print("Enter the Numher of Students: ");
		NumberofStudent = console.nextInt();
		
		System.out.print("\nEnter the Number of Exams: ");
		NumberofExam = console.nextInt();
		
		int[] idNumber = new int[NumberofStudent];
		int[] Exam = new int[NumberofExam];
		
		
		System.out.println("\nEnter the Id Number of the Students: ");
		for(int i = 0 ; i < NumberofStudent ; i++)//Inputted ID Number of students from the user
		{
			idNumber[i] = console.nextInt();
		}
		
		for(int i = 0 ; i < NumberofStudent ; i++)//prints the id number and enters the score of the student
		{
			System.out.println("\nId Number: " + idNumber[i]);
			System.out.println("Enter the Score of the Sudent: ");
			for(int j = 0; j < NumberofExam ; j++)
			{
				Exam[j] = console.nextInt();
			}
			
		}
		
		int[] AverageScore = new int[NumberofExam];
		
		int SumofAllExams = 0;
		int TotalofGivenExam = 0;
		TotalofGivenExam = Exam.length;
		
		for(int j = 0; j < NumberofExam ; j++)//calculates the sum of the exams of each students
		{
			SumofAllExams += Exam[j];
		}
		
		for(int i = 0; i < NumberofExam ; i++)//calculates the average scores of each students
		{
			AverageScore[i] = SumofAllExams / TotalofGivenExam;
		}
		
		System.out.println("\n\n\t\t~RESULT~");
		
		for(int i = 0; i < NumberofStudent ; i++)//prints out the id number of each students
		{
			System.out.println("\n\tId Number: " + idNumber[i]);
			
			System.out.println("\tScore of all the Exams: ");
			for(int j = 0 ; j < NumberofStudent ; j++)	//prints out the scores exams of each students
			{
				k++;
				System.out.print("\tExam No." + k);
				System.out.println("  \tScore: \t" + Exam[j]);
			}
			System.out.println("\tAverage Score: " + AverageScore[i]);
			k = 0;
		}
		
		
	}

}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Can you give a full rundown of what this is supposed to do? Your description is a little cryptic. 

 

What is being stored where/how?

What does the user input do?

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

the program should work like this:

 

image.png.18a1ab0f3590988df656b3b9651b0138.png

2 minutes ago, Slottr said:

Can you give a full rundown of what this is supposed to do? Your description is a little cryptic. 

 

What is being stored where/how?

What does the user input do?

 

Link to comment
Share on other sites

Link to post
Share on other sites

The user has 2 students and 2 exams which creates the number sets the value to the array.

then the user inputs the id number (2 students) then inputs the exams(2 exams).

 

the program would calculate the sum of each students scores and gets the average.

 

the program would individualy prints the id number, scores and the average.

 

sorry for my bad english

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, REDRIDINGHOODS said:

The user has 2 students and 2 exams which creates the number sets the value to the array.

then the user inputs the id number (2 students) then inputs the exams(2 exams).

 

the program would calculate the sum of each students scores and gets the average.

 

the program would individualy prints the id number, scores and the average.

 

sorry for my bad english

Do you have to use arrays here?

It seems like creating a new object which has values for student number, and test scores would be more suitable.

 

Or a dictionary 

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Slottr said:

Do you have to use arrays here?

It seems like creating a new object which has values for student number, and test scores would be more suitable.

 

Or a dictionary 

can you teach me how to create an object and explain how it works?

Link to comment
Share on other sites

Link to post
Share on other sites

Your mistake is that you have a single Exam array that you are loading the scores into. Which means if you have two students, you fill the array with student 1's scores, then overwrite it with student 2's scores.

 

You need multiple scores arrays, one per student.

 

You can do this two ways:

 

#1: a 2-dimensional array. E.g.

int scores = new int[a][b]

when you access this array, e.g. scores[a] = 5 then a is the index for the student and b is the index for the score.

 

#2: Create a "Student" object, that contains a scores array. Then in your main function create an array of Student objects.  This is what Slottr recommended

This is more complicated than option 1 but is the more correct approach. Better learning experience too.

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, REDRIDINGHOODS said:

can you teach me how to create an object and explain how it works?

Basically every data structure you create is a new object.

 

So say we create an object "Foo"

 

Foo MyNewItem = new Foo;

 

will create your new structure (object) of type foo. "MyNewItem" being the name of your newly created structure. 

 

So foo can be something such as an array. 

 

Creating your own structure might be a little advanced to where you are, so stick with the inbuilt java stuff.

 

 

Back to your initial question:

I don't have access to an IDE right now, but one thing I notice is that you're not storing your new values right. You'll be overwriting the initial two values every time, and when you try to access higher values of the array (which don't exist) you'll be given memory locations instead of input integers. 

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, Vectorspace said:

Your mistake is that you have a single Exam array that you are loading the scores into. Which means if you have two students, you fill the array with student 1's scores, then overwrite it with student 2's scores.

 

You need multiple scores arrays, one per student.

 

You can do this two ways:

 

#1: a 2-dimensional array. E.g.


int scores = new int[a][b]

when you access this array, e.g. scores[a] = 5 then a is the index for the student and b is the index for the score.

 

#2: Create a "Student" object, that contains a scores array. Then in your main function create an array of Student objects.  This is what Slottr recommended

This is more complicated than option 1 but is the more correct approach. Better learning experience too.

 

what if I had to enter the number students and the number of exams then store the each students scores in the array? like this

 

 

(5).mkv

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, REDRIDINGHOODS said:

what if I had to enter the number students and the number of exams then store the each students scores in the array? like this

 

 

(5).mkv 7.63 MB · 7 downloads

Can't see your file, but that sounds like you're on the right track if you did want to use an array 

 

You can use a 2D array and initialize the array to be # of exams +1 to accommodate for the student number for each row.

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to comment
Share on other sites

Link to post
Share on other sites

25 minutes ago, Vectorspace said:

Your mistake is that you have a single Exam array that you are loading the scores into. Which means if you have two students, you fill the array with student 1's scores, then overwrite it with student 2's scores.

 

You need multiple scores arrays, one per student.

 

You can do this two ways:

 

#1: a 2-dimensional array. E.g.





int scores = new int[a][b]

when you access this array, e.g. scores[a] = 5 then a is the index for the student and b is the index for the score.

 

#2: Create a "Student" object, that contains a scores array. Then in your main function create an array of Student objects.  This is what Slottr recommended

This is more complicated than option 1 but is the more correct approach. Better learning experience too.

 

It can be done with a one dimensional array which lengths is "NumberofExam" times longer than the id list. Index calculation for 2d arrays look like this: width * a + b or "NumberofExam" * a + b


 

 

 

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

shadow_ray - would also work, but is the less correct approach and requires more complicated array looping

 

REDRIDINGHOODS - you can read the student and exam counts, and then use those to define the size of your 2d array:

studentCount = console.nextInt();
examCount = console.nextInt();

int[][] scores = new int[studentCount][examCount];

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Vectorspace said:

shadow_ray - would also work, but is the less correct approach and requires more complicated array looping

I agree but OP is just learning about arrays.. I felt the need to mention it.

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

one more thing

I believe common java naming conventions use lowerCamelCase for local varriables and UpperCamelCase for classes.

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Vectorspace said:

shadow_ray - would also work, but is the less correct approach and requires more complicated array looping

 

REDRIDINGHOODS - you can read the student and exam counts, and then use those to define the size of your 2d array:


studentCount = console.nextInt();
examCount = console.nextInt();

int[][] scores = new int[studentCount][examCount];

 

thank you for the tip and explaning to me how 2d array works. I got my program fixed and ready to function well. You made my day thank you!

Link to comment
Share on other sites

Link to post
Share on other sites

11 minutes ago, shadow_ray said:

I agree but OP is just learning about arrays.. I felt the need to mention it.

the thing is my professor didn't teach us the 2d arrays and I didn't know that it exist. Thank you for the tip also

Link to comment
Share on other sites

Link to post
Share on other sites

31 minutes ago, Slottr said:

Basically every data structure you create is a new object.

 

So say we create an object "Foo"

 


Foo MyNewItem = new Foo;

 

will create your new structure (object) of type foo. "MyNewItem" being the name of your newly created structure. 

 

So foo can be something such as an array. 

 

Creating your own structure might be a little advanced to where you are, so stick with the inbuilt java stuff.

 

 

Back to your initial question:

I don't have access to an IDE right now, but one thing I notice is that you're not storing your new values right. You'll be overwriting the initial two values every time, and when you try to access higher values of the array (which don't exist) you'll be given memory locations instead of input integers. 

I will try to learn this type of method but I still don't understand how an object works. I will try to learn on how this works. Also thank you for giving me a tip. I hope you have a nice day!

Link to comment
Share on other sites

Link to post
Share on other sites

You're welcome.

 

And if you're interested, here is my solution:

 

Spoiler

package academy.learnprogramming;

import java.util.Scanner;

//https://linustechtips.com/topic/1343338-please-help-me-to-display-the-inputted-data-in-array/

public class Main {

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int studentCount;
        int examCount;

        System.out.print("Enter the number of Students: ");
        studentCount = input.nextInt();
        input.nextLine();

        System.out.print("\nEnter the number of Exams: ");
        examCount = input.nextInt();
        input.nextLine();

        int[] studentIds = new int[studentCount];
        int[][] scores = new int[studentCount][examCount];

        System.out.println("\nEnter the Id Number of the Students: ");
        for (int i = 0; i < studentCount; i++) {
            studentIds[i] = input.nextInt();
            input.nextLine();
        }

        for (int i = 0; i < studentCount; i++) {
            System.out.println("\nId Number: " + studentIds[i]);
            System.out.println("Enter the score of the Student:");
            for (int j = 0; j < examCount; j++) {
                scores[i][j] = input.nextInt();
                input.nextLine();
            }
        }

        System.out.println("\n\n\t\t~RESULT~");

        for (int i = 0; i < studentCount; i++) {
            System.out.println("\n\tId Number: " + studentIds[i]);
            System.out.println("\tScore of all the Exams:");
            int sum = 0;
            for (int j = 0; j < examCount; j++) {
                sum += scores[i][j];
                System.out.println("\tExam No." + (j+1) + "\tScore:  " + scores[i][j]);
            }
            System.out.println("\tAverage Score: " + (sum/examCount));
        }
    }
}

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×