I have a homework assignment and the program generates a random number of students taking a random number of tests. The user must enter the students names and test scores. Once that is done the program will print on the screen : STUDENT REPORT Scores for Fred:
Test #1: 78
Test #2: 80
Average for Fred: 79.0
Scores for Sue:
Test #1: 91
Test #2: 94
Average for Sue: 92.5
... and so on depending on what number of students and tests you get.
I get everything right up until the average part how can I fix it?
Here's my code:
public static void populateNames(String[] names)
{
for(int i = 0; i<names.length; i++)
{
out.print("Enter student " + (i+1) + " name: ");
names[i] = keyboard.next();
}
}
// Code your 3 methods below...
//Ask the user for the student name as well as the test scores
public static void populateTestScores(String[] names, int[][] scores)
{
out.println();
for(int i=0; i<names.length; i++)
{
out.println();
out.println("Entering scores for: " + names[i]);
for(int s=0; s<scores[0].length; s++)
{
out.print("Enter score for test #" + (s+1) + ": ");
scores[i][s] = keyboard.nextInt();
}
}
out.println();
}
//Print each studdent test scores and ther average
public static void printStudentReport(String[] names, int[][] scores)
{
out.println("STUDENT REPORT");
for(int i=0; i<names.length; i++)
{
out.print("Scores for " + names[i] + ": ");
out.println();
for(int s=0; s<scores[0].length; s++)
{
out.println("Test #" + (s + 1) + ": " + scores[i][s]);
}
out.println();
int s=0;
if(s<scores[0].length)
{
s++;
double sum = 0;
sum += scores[i][s];
double average = sum / scores[0].length;
out.println("Average for " + names[i] + ": " + average);
out.println();
}
}
out.println();
}
The problem is in the way you're computing sum in printStudentReport: it only contains the second element in the list of scores because you're creating and adding to sum after the for loop (instead of creating before the loop and adding in it).
I'd rearrange that method to (reformatted for compactness):
// Print each studdent test scores and ther average
public static void printStudentReport(String[] names, int[][] scores) {
out.println("STUDENT REPORT");
for (int i = 0; i < names.length; i++) {
out.print("Scores for " + names[i] + ": ");
out.println();
double sum = 0;
for (int s = 0; s < scores[0].length; s++) {
out.println("Test #" + (s + 1) + ": " + scores[i][s]);
sum += scores[i][s];
}
out.println();
if (0 < scores[0].length) {
double average = sum / scores[0].length;
out.println("Average for " + names[i] + ": " + average);
out.println();
}
}
out.println();
}
Related
I'm trying to make a code that takes a users input and prints their schedule, but I'm running into a problem with my do-while loop.
My program will not rerun. I'm getting an error that says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)
Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String rerun;
do {
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("How many courses do you have?");
int numCourse = input.nextInt();
input.nextLine();
String[][] timetable = new String[numCourse][2];
for (int j = 0; j < numCourse; j++) {
System.out.println("What is the name of your course #" + (j + 1) + "?");
String course = input.nextLine();
timetable[j][0] = course;
System.out.println("What is your teachers name for " + course + "?");
String teacher = input.nextLine();
timetable[j][1] = teacher;
}
System.out.println("Hello " + name + ", here is your timetable:");
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
System.out.println("Would anyone else like to print their schedule? (yes/no)");
rerun = input.next();
}while(rerun.equalsIgnoreCase("yes"));
System.out.println("Goodbye!");
}
}
Problem is in second for loop where you display your from array. put next() inplace of nextLine() because sometimes it skip the position.
Change
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
To
for (int i = 0; i < numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
Suppose your numCorse is 2. In your code, loop start from 0 and terminate after 2 so, Your loop working right while i is 0 and 1 but if i is going to 3 you get exception ArrayIndexOutOfBound.
So I'm trying to create a program that takes in the student's GPA and prints out if they are graduating at an honor's level, graduating, or not graduating. I have most of the code figured out, but I am trying to make it so that ALL of the input is first, and then it will go back and print out whether each student is graduating. But what I am getting is printing out the graduation status for each student immediately after the input for that student.
I'm getting this:
Enter the number of GPAs: 3
GPA #0: 3.99
Student #0: Summa Cum Laude
GPA #1: 3.1
Student #1: Graduating
GPA #2: 2
Student #2: Graduating
When I want this:
Enter the number of GPAs: 3
GPA #0: 3.99
GPA #1: 3.1
GPA #2: 2
Student #0: Summa Cum Laude
Student #1: Graduating
Student #2: Graduating
Here is my code:
System.out.print("Enter the number of GPAs: ");
int size = sc.nextInt();
int array[] = new int[size];
double gpa;
for (int i = 0; i < size; i++) {
System.out.print("GPA #"+ i + ": " );
gpa = sc.nextDouble();
if (gpa >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (gpa >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (gpa >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (gpa >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}}
First you need to fill the array with values GPA we declare an array of double
double array[] = new double[size];
We iterate through for loop and we ask user to enter GPA and we fill our array with those values
for (int i = 0; i < size; i++) {
System.out.print("GPA #" + i + ": ");
gpa = sc.nextDouble();
array[index++] = gpa;
}
Now we have array with our values filled so what should we do know we print it by checking array values with our if statements.
for(int i=0;i<array.length;i++){
if (array[i] >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (array[i] >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (array[i] >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (array[i] >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}
}
FULL CODE
System.out.print("Enter the number of GPAs: ");
int size = sc.nextInt();
double array[] = new double[size];
double gpa;
int index = 0;
for (int i = 0; i < size; i++) {
System.out.print("GPA #" + i + ": ");
gpa = sc.nextDouble();
array[index++] = gpa;
}
for(int i=0;i<array.length;i++){
if (array[i] >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (array[i] >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (array[i] >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (array[i] >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}
}
It sounds like you want to have one list of GPA's immediately followed by another list of status'. If that is the case, then you have 2 separate lists, which will require 2 separate loops.
Make a loop that prints out your GPA's, then after that loop finishes, have another loop that prints out the status'. Also, you will need some way to store those values from the first loop. Maybe an array?
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
String[] array2 = new String [10]; // New array that saves up to 10 elements(treatments)
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
int n = array.length;
for (int i=0; i<n; i++) {
for (int j=0; i<n ; j++) {
System.out.println();
treatment = input.nextInt();
if (treatment==1) {
cost += Integer.parseInt(array[i][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==2) {
cost += Integer.parseInt(array[i+1][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==3) {
cost += Integer.parseInt(array[i+2][1]);
System.out.print("Total cost so far: " + cost);
}
}
}
How do I move on from here? I figured that I have to store the input in the new array and exit the loop after 10 treatments or add an option to the user to print out the receipt when they're done.
The receipt needs to print all the chosen treatments along with the cost for each individual treatment. I will also need to add a variable to add a total amount for all the chosen treatments.
Here it is what you are trying to do, As the treatments are fixed so you can just index them as 0, 1, 2. One thing you can do is to make a hashmap in which you can store the treatment name and its cost (String,int) every time the user wants to enter.
Look at the code below
import java.util.*;
import java.util.HashMap;
public class treatment {
public static void main(String []args) {
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
// New array that saves up to 10 elements(treatments)
HashMap<String, Integer> treat = new HashMap<String, Integer>();
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
int n = array.length;
int i =0;
char c = '\0';
do {
System.out.println("\n\nControl" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
System.out.println("Exit: " + "-1");
System.out.println();
System.out.print("Enter treatment value (1, 2, 3): ");
treatment = input.nextInt();
if (treatment==1){
i = 0;
cost += Integer.parseInt(array[0][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==2) {
i = 1;
cost += Integer.parseInt(array[1][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==3) {
i = 2;
cost += Integer.parseInt(array[2][1]);
System.out.println("\nTotal cost so far: " + cost);
}
treat.put(array[i][0], cost);
} while (treatment != -1);
System.out.println("Total COst is : " + cost);
System.out.println("The treatements you opt for are:\n");
System.out.println(treat);
System.out.println("\n");
}
}
Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}
I've been working on a small bit of code that helps me calculate performance of a movie's Box-Office weekend. I want it to require the
Name of the movie
How much it'll cost to use
How much it's predicted to make that weekend
Then I want it to output all the above information, with the addition of each movie's performance. Well, I'm having issues with it saving multiple String[] values as well as int[] values. I can remove the String lines, and all the int[]'s (both the price and the prediction) work fine, or I can remove the int[]'s and the String[] works fine. Can anyone help me find my errors?
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[15];
int[] moviePrice = new int[15];
int[] moviePrediction = new int[15];
int[] moviePreformance = new int[15];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = console.nextInt();
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = console.nextInt();
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
When you used nextInt() and entered a number you also enterd a new line character, so the next time you called nextLine() this new line character was your next input waiting.
You could fix this by always using nextLine, or by adding a call for nextLine.
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[2];
int[] moviePrice = new int[2];
int[] moviePrediction = new int[2];
int[] moviePreformance = new int[2];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = Integer.parseInt(console.nextLine());
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = Integer.parseInt(console.nextLine());
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
This should fix the issue:
moviePrice[i] = console.nextInt();
console.nextLine();
moviePrediction[i] = console.nextInt();
console.nextLine();
console.nextInt() only reads the number, not the rest of the line, like carriage return.