In: Computer Science
in java Jimmy wants to store course grades and corresponding
student last names
using two parallel arraylists (Double and String).
She also wants to identify the average of all the grades.
Use a while loop.
Prompt the user for each grade and use -1 as the sentinel.
Ask for the student name if -1 has not been entered for the grade.
Be sure to output the average of the grades. (**Hint: You will need to figure out the sum first)
Use a for loop to output the name and grade for each student to look like this:
Grade: 99 Name: Billy
Grade: 98 Name: Sandy
etc..
import java.util.*;
public class Solution{
//driver function
public static void main(String []args){
//scanner object
Scanner sc = new Scanner(System.in);
//array list to store grades
ArrayList<Double> grades= new
ArrayList<Double>();
//array list to store names
ArrayList<String> names= new ArrayList<String>();
//to store total sum of grades
double sum=0;
//to count total inputs
int tot=0;
//loop until user enters -1
while(true){
//ask user to input grade
System.out.print("Enter grade: ");
//input grade
double grade=sc.nextDouble();
sc.nextLine();
//if grade is -1 then end
if(grade==-1){
break;
}
//otherwise
else{
//increment total count
tot++;
//add it to sum
sum+=grade;
//add to array list
grades.add(grade);
//ask user to enter name
System.out.print("Enter name: ");
//input name
String name=sc.nextLine();
//add it to list
names.add(name);
}
}
//calculate average
double avg=sum/tot;
//for each entry, print name and grade
for(int i=0;i<tot;i++){
System.out.println("Grade: "+grades.get(i)+" Name:
"+names.get(i));
}
//print average
System.out.println("Average of all grades is: "+avg);
}
}
Enter grade: 99
Enter name: Billy
Enter grade: 98
Enter name: Sandy
Enter grade: -1
Grade: 99.0 Name: Billy
Grade: 98.0 Name: Sandy
Average of all grades is: 98.5
CODE
INPUT/OUTPUT
So if you still have any doubt regarding this solution please feel free to ask it in the comment section below and if it is helpful then please upvote this solution, THANK YOU.