Using an Array's Element to Populate Another Array - Java - java

I am learning Java on my own and have just finished learning the basics of arrays, or so I think. I want to create a class grade sheet that keeps each student's grades and average. I have a for loop that asks each of the 10 students to enter their 4 test grades. Once I get those 4 grades, I take the average. I then store the student's grades and average into an array, one array per student. I essentially create 10 arrays with these 5 elements, for each student using the for loop. I now want to take the 5th element, the average of the 4 grades, from each student's array and populate another array called averages so I can perform other calculations. Is this possible with my logic? I think I could hard code 10 arrays, 1 for each student like so:
double averages[] = {student1[4], student2[4], ..., student10[4]};
Isn't this a bad way to go about this though? Any constructive help or guidance would be appreciated. Please do not post code that gives away the answer, as I won't learn from that. I just want a hint in the right direction. :)
Here's my code up until the point of confusion:
import java.util.Scanner;
public class ClassAverages {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double grade1 = 0.0, grade2 = 0.0, grade3 = 0.0, grade4 = 0.0, average = 0.0;
// get grades from each of the 10 students
for (int student = 1; student <= 3; student++) {
System.out.println("Student " + student);
System.out.println("---------\n");
System.out.print("Enter the first grade: ");
grade1 = keyboard.nextDouble();
while (grade1 < 0) { // input validation for grade 1
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade1 = keyboard.nextDouble();
}
System.out.print("Enter the second grade: ");
grade2 = keyboard.nextDouble();
while (grade2 < 0) { // input validation for grade 2
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade2 = keyboard.nextDouble();
}
System.out.print("Enter the third grade: ");
grade3 = keyboard.nextDouble();
while (grade3 < 0) { // input validation for grade 3
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade3 = keyboard.nextDouble();
}
System.out.print("Enter the fourth grade: ");
grade4 = keyboard.nextDouble();
System.out.println();
while (grade4 < 0) { // input validation for grade 4
System.out.print("You entered a negative value for grade. Please re-enter a positive grade: ");
grade4 = keyboard.nextDouble();
System.out.println();
}
// calculate the current student's average
average = (grade1 + grade2 + grade3 + grade4) / 4;
// for each student, 1 to 10, create an array with their 4 grades and average
double studentX[] = { grade1, grade2, grade3, grade4, average };
System.out.println("SCORE 1\t\tSCORE 2\t\tSCORE 3\t\tSCORE 4\t\tAVERAGE");
System.out.print(studentX[0] + "\t\t");
System.out.print(studentX[1] + "\t\t");
System.out.print(studentX[2] + "\t\t");
System.out.print(studentX[3] + "\t\t");
System.out.print(studentX[4] + "\n");
System.out.println();
// I want to use each student's average for each corresponding element in the averages array
// create an array of all student's averages
// double averages[] = {student1average, student2average,...student10average} ???
}
}
}
OUTPUT AS OF NOW:
Student 1
---------
Enter the first grade: 100
Enter the second grade: 100
Enter the third grade: 100
Enter the fourth grade: 100
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
100.0 100.0 100.0 100.0 100.0
Student 2
---------
Enter the first grade: 90
Enter the second grade: 90
Enter the third grade: 90
Enter the fourth grade: 80
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
90.0 90.0 90.0 80.0 87.5
Student 3
---------
Enter the first grade: 100
Enter the second grade: 100
Enter the third grade: 90
Enter the fourth grade: 80
SCORE 1 SCORE 2 SCORE 3 SCORE 4 AVERAGE
100.0 100.0 90.0 80.0 92.5

You could use a for loop. However this will require you to have a collection of items to iterate through. I think the best way for you to do this is to organize your students into their own separate class (give that class all the grades as parameters in its constructor and have it do the calculations for average within that class).
So if you call your class student then your constructor could look like thisstudent(int grade1, int grade2, int grade3, int grade4). Use these parameters to calculate the average for each student object.
Then in your ClassAverage class just instantiate new student objects as you want and add them to an array of student objects and then its as simple as iterating through the array of student, extracting the average field that you created for each student object (extract this simply by stating studentName.average, assuming you named your average field average in the student class).
So by the end you should have something that looks like this. Let's assume that the array of student objects is called studentArray
int[] averageArray = new int[studentArray.length];
for (int i = 0; i < studentArray.length; i++){
averageArray[i] = studentArray[i].average;
}
Good luck!

Arrays are very bad form of storing information. Mostly because they don't contain logic that uses data inside this arrays and any other code can make that data invalid because array doesn't check what values you give it. This is what classes are for: to have data and code that works with it in one place, and to protect data from changes from other places in code.
So for your case arrays are OK for fields of the same type(for example, array of students is OK), but not for values of that types(array of arrays of students grades is NOT OK). So what you should do here is to use a class:
class Student
{
int grades[] = new int[4];
public Student(int grade1, grade2, int grade3, int grade4)
{
grades[0] = grade1;
grades[1]=grade2;
grades[2]=grade3;
grades[3]=grade4;
}
public double average()
{
double result = 0;
for(int i =0; i<grades.count; i++)
result += grades;
return result / grades / count;
}
// and so on
}
They allow you to take logic inside object, sou you can use it like this:
Student albert = new Student(5, 4, 2, 1);
System.out.println(albert.avarage()); // prints 3

Related

Create a user input array, find the average of rows in the array, and list those averages in a new Array?

So, I'm having trouble on the bit where the averages need to be stored into an Array. I'm able to take input from the user for each student and so forth. I can then properly calculate the grade, but then it wont give me the array of averages. I kind of understand why it's happening, but I have no clue on how to fix it if i'm being honest. Ive hit the books, the professors slides, and google as much as I can.
import java.util.Arrays;
import java.util.Scanner;
public class StudentGradeDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number of students: ");
int rows = input.nextInt();
System.out.print("Enter a number of scores: ");
int columns = input.nextInt();
double[][] gradesArray = new double[rows][columns];
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.printf("Please enter score %d for the student %d: ", j + 1, i +1);
gradesArray[i][j] = input.nextDouble();
}
}
double rowSum = 0;
double [] scoreArray = new double[columns];
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
rowSum = rowSum + gradesArray[i][j];
scoreArray[j] = (double)rowSum/columns;
}
System.out.printf( "The average score for student %d is: " + (double)rowSum/columns + "%n", i+1 );
rowSum = 0;
}
System.out.println(Arrays.toString(scoreArray));
}
}
my output looks like,
Enter a number of students: 5
Enter a number of scores: 2
Please enter score 1 for the student 1: 34
Please enter score 2 for the student 1: 65
Please enter score 1 for the student 2: 34
Please enter score 2 for the student 2: 76
Please enter score 1 for the student 3: 54
Please enter score 2 for the student 3: 23
Please enter score 1 for the student 4: 87
Please enter score 2 for the student 4: 65
Please enter score 1 for the student 5: 87
Please enter score 2 for the student 5: 56
The average score for student 1 is: 49.5
The average score for student 2 is: 55.0
The average score for student 3 is: 38.5
The average score for student 4 is: 76.0
The average score for student 5 is: 71.5
[43.5, 71.5] <- this should be the array, but I dont know what it is. Please go easy on me, its my first semester and I'm really struggling. Thanks for the help.
This is exactly what you ask for!
Arrays.toString(scoreArray)
prints the contents of your array. scoreArray has two entries, and those get printed, as [43.5, 71.5].
In other words: your code does exactly what you want.

How to enter a character to stop a loop

I need to write code that calculates the average of inputs (int) a user has entered. However, the problem is that I also have to allow the user to enter as many inputs as they want and stop when they enter a character(letter).
I can do this problem if there was a given limit I could use, but because the limit could be anything I am having trouble writing a formula that could calculate the average since the number of inputs could be different between any user.
import java.util.Scanner;
public class AvgGrades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
float total=0, avg;
int grades = input.nextInt();
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextInt();
total = total + grades[i];
}
input.close();
avg = total/grades.length;
System.out.println("Average student grade is "+avg);
}
}
The inputs are:
30.0
45.6
23.8
78.75
90
92
67.5
10.65
88
c
The output should be:
Enter as many student grades as you like. Enter a character to stop.
Average student grade is: 58.477777777777774
My output is that the code just does not run.
Here's a sketch of the process. I'll leave for you the details of turning that into a complete program.
float total = 0;
int count = 0;
while (scanner.hasNextFloat()) {
float num = scanner.nextFloat();
total += num;
count++;
}
float average = total / count;
You don't need to store the individual numbers.

grade avg calculator not returning correct answer

This is a program to calculate average grades and I cant figure out whats wrong with my code. It is returning the wrong answer.
Editing post to remove personal information.
:
/**
* This program will calculate grade average of user input
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade();
}
public static void avgGrade() {
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double grade;
double total = 0;
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade= keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Output:
Please input the grade
100
Please input the grade
50
Please input the grade
-9
Sum is 50.0
The average of the 2 grades are 50.00
Sum should have been 150 and average 75.
The problem is that you are reading a grade from the user before the while loop begins and you are ignoring this value afterwards.
You should remove those 2 lines and things will work as expected. I commented those lines in the snippet below to explicitely show you the problem.
public static void avgGrade() {
Scanner keyboard = new Scanner(System.in);
double count = 0;
double avgGrade = 0;
double grade;
double total = 0;
// System.out.println("Please input the grade");
// grade = keyboard.nextDouble();
while(true){
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
count = count + 1;
if (grade < 0) break;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
As a side note, you should always try to minimize the scope of each of your variable. Here, the grade variable is only use inside the while loop so you can directly write double grade = keyboard.nextDouble(); and remove the declaration in the beginning of the method.
You are not adding the first grade which you are accepting outside of the while loop to the total.
Also there is no point in incrementing the count, if the grade is not acceptable, so increment your count only after the grade check.
You can rewrite your while block something like
while (true) {
System.out.println("Please input the grade");
grade = keyboard.nextDouble();
if (grade < 0)
break;
count = count + 1;
total += grade;
}
avgGrade = total / count;
System.out.println("Sum is " + total);
System.out.printf("The average of the %.0f grades are %.2f ", count,
avgGrade);
}
Thanks guys. Here is the final code
/**
* This program will calculate grade average of user input
*
* Date: 10/2/2015
*/
import java.util.Scanner;
public class GradeAVG {
public static void main(String[] args) {
avgGrade()
}
public static void avgGrade()
{
Scanner keyboard = new Scanner (System.in);
double count = 0;
double avgGrade = 0 ;
double total = 0;
while(true){
System.out.println("Please input the grade");
double grade= keyboard.nextDouble();
if (grade < 0) break;
count = count + 1;
total += grade;
avgGrade = total/count;
}
System.out.println ("Sum is " +total);
System.out.printf("The average of the %.0f grades are %.2f " ,count ,avgGrade);
}
}
Several problems:
First, you do two assignments into grade before first reading from it (first one before the while loop and second inside the while loop), so the first input will be ignored entirely
Second, you increment the count variable before checking whether to break the while loop, so you end up with count higher by 1 than should be
Third, the average is computed inside the loop and will not be recalculated in the last (partial) iteration
The program will go like this:
input: 100, count: 0, total: 0, avg: 0
input was ignored
input: 50, count: 1, total: 50, avg: 50
input: -9, count: 2, total: 50, avg: 50
loop exit, but incremented count before; did not recalculate avg

I need to use double instead of int for my outcome to be correct. Why? (Java)

Today i tried to make a simple program in Java that gives me the average of the numbers i entered.
The problem is that if i use int added (as shown below), i don't get the same answer as when i use double added.
Code:
public class Main {
public static void main(String[] args) {
int amount;
int number;
int added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.0
When i use double, i get the right answer:
public class Main {
public static void main(String[] args) {
int amount;
int number;
double added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result when i use double added instead of int added:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.5
Why does this happen and what should i do to avoid it?
To me it seems like added could be an int because i don't add up decimals but i add up whole numbers.
Thank you in advance.
In order for added/amount to return a non integer, either added or amount must be float or double or cast to either of them.
When both are int, an integer division takes place and the result is only converted to double after the division in order to be stored in your double average variable.
The result of a division in which both elements are integer, will be an integer. At least one of them needs to be a float or a double for the result of the division to be a floating point number.

Can I use math ceil with input string in Java?

Is it possible to make this output in Java?
Using Looped statements while asking for input Grades for each student then use Ceiling to identify who has the highest grade.
Student Number Grades
Student 1 _
Student 2
Student 3
Student 4
Student 5
Student 6
Student 7
Student 8
Student 9
Student 10
The student with the highest Grade is: (e.g) Student 8
Yes, you can use a loop:
Scanner scan = new Scanner(System.in);
double max = -1; // grades can't be negative
int maxStudent = 0;
double[] grades = new double[10];
for (int i = 1; i < grades.length; i++) {
System.out.println("Please enter grade for Student "+i);
grades[i] = scan.nextDouble();
if (grades[i] > max) {
max = grades[i]
maxStudent = i;
}
}
Math.ceil(double a)
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. So unless you're trying to round up, you won't need ceil. Although to answer the title question, you can use Math.ceil on an input string, assuming the string can be parsed into a double.
For instance, these are all true statements:
Math.ceil(99) == 99.0
Math.ceil(99.01) == 100.0
Math.ceil(99.99) == 100.0
Can ceiling only be used in one number? or it can be used with multiple numbers like that.
You can not use Math.ceil on any sort of collection to find the highest value as you wish to do. Loop through all values an keep track of the highest

Categories

Resources