I would like to create a 3d array with the already existing arrays(Score, CourseRating, and SlopeRating). I would like to do so, so that I can match the Scores with their Ratings. If it is not possible, I was thinking I could maybe find the index of the score, and match it with the Course and Slope rating so that I can calculate the Handicap Index.
import java.util.Arrays;
import java.util.Scanner;
public class RoughDraft {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count;
int[] Scores;
double[] SlopeRating;
double[] CourseRating;
System.out.print("\nHow many scores would you like to enter?: ");
count = scnr.nextInt();
// ------ adds Scores, Course Rating and Slope Rating to Arrays ------ //
Scores = new int[count];
CourseRating = new double[count];
SlopeRating = new double[count];
if(count >= 5 && count <= 20) {
for(int i = 0; i < count; i++) {
System.out.printf("\nEnter Score #%d: ", i + 1);
if(scnr.hasNextInt()) {
Scores[i] = scnr.nextInt();
}
System.out.printf("Enter Course Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
CourseRating[i] = scnr.nextDouble();
}
System.out.printf("Enter Slope Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
SlopeRating[i] = scnr.nextDouble();
}
}
}
else {
System.out.print("Enter a minimum of 5 scores and a maximum of 20 scores.");
main(args);
}
System.out.print("\nScores: " + Arrays.toString(Scores));
System.out.print("\nCourse Ratings: " + Arrays.toString(CourseRating));
System.out.print("\nSlope Rating: " + Arrays.toString(SlopeRating));
}
}
Related
Need to get the index of the largest value in teamScores[] and print the associated string with the matching index from teamNames[]. This is really starting to get on my nerves. I had been able to successfully get the right value for the scores printed but it kept printing the wrong team. When I was trying to troubleshoot I was getting the right team but the wrong score. I am absolutely lost and have no other ideas. Anybody offer some advice? I have to use two separate arrays so I cannot just reduce it to one array. I also have to use a for loop to retrieve the values, so I can't do like I did with the lowScore.
public class SmithJustin_Asgn6 {
public static int highScore(int[] teamScores, int highIndex) {
int max = teamScores[0];
for(int i = 0; i < teamScores.length; i++) {
if(max < teamScores[i]) {
max = teamScores[i];
highIndex = i;
}
}return highIndex;
}
public static int lowScore(int[] teamScores) {
Arrays.sort(teamScores);
int low = teamScores[0];
return low;
}
public static void main(String[] args) {
int highIndex = 0;
Scanner userInput=new Scanner(System.in);
Scanner scoreInput=new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams=scoreInput.nextInt();
int [] teamScores= new int[teams];
String [] teamNames= new String[teams];
for(int i = 0; i < teams; i++) {
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
String teamName=userInput.nextLine();
teamNames[i]=teamName;
System.out.print("Enter Team's score (400-1000): ");
int teamScore=scoreInput.nextInt();
teamScores[i]=teamScore;
System.out.println();
}
highScore(teamScores, highIndex);
lowScore(teamScores);
System.out.println();
System.out.println("The high score is "+ teamScores[highScore(teamScores, highIndex)] +" by team " + teamNames[highScore(teamScores, highIndex)] + " and the low score is "+ lowScore(teamScores) +".");
userInput.close();
scoreInput.close();
}
}
Been trying every way to slice it and I am completely stuck
You can create a class to store team name and its score. Then sort the array of class objects based on a comparator. Also, you don't need to use two Scanner objects.
class Team
{
public int score;
public String name;
}
class SmithJustin_Asgn6 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams = userInput.nextInt();
Team[] teamArray = new Team[teams];
for(int i = 0; i < teams; i++) {
teamArray[i] = new Team();
userInput.nextLine();
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
teamArray[i].name = userInput.nextLine();
System.out.print("Enter Team's score (400-1000): ");
teamArray[i].score = userInput.nextInt();
System.out.println();
}
userInput.close();
Arrays.sort(teamArray, new Comparator<Team>() {
#Override
public int compare(Team o1, Team o2) {
return Integer.compare(o1.score, o2.score);
}
});
System.out.println();
System.out.println("The high score is "+ teamArray[teams - 1].score +" by team " + teamArray[teams - 1].name + " and the low score is "+ teamArray[0].score +".");
}
}
As mentioned by #Andrey your Arrays.sort is the main culprit. You need a logic to get the low score index the same as you have done for high score index.
public static int lowScore(int[] teamScores, int lowIndex) {
// Arrays.sort(teamScores);
int low = teamScores[0];
//logic to low score's index
return lowIndex;
}
After you have both the indexes, you can easily get values from respective arrays using them.
In your main method you are calling the same methods multiple times instead of that you can do
int lowIndex = 0;
highIndex = highScore(teamScores, highIndex);
lowIndex = lowScore(teamScores, lowIndex);
System.out.println();
System.out.println("The high score is " + teamScores[highIndex] + " by team " + teamNames[highIndex] + " and the low score is " + teamScores[lowIndex] + ".");
Start learning stream. Its easy and fun ;).
int h1 = IntStream.range(0, teamScores.length)
.reduce((i, j) -> teamScores[i] > teamScores[i] ? i : j)
.getAsInt();
int lowScore = Arrays.stream(teamScores).min().getAsInt();
System.out.println("The high score is " + teamScores[h1] + " by team " + teamNames[h1]+ " and the low score is " + lowScore + ".");
I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}
My assignment asks me to write a program that will let the user input 10 players' name, age, position, and batting average. (For the sake of less confusion, I made the program input only 3 players). The program should then check and display statistics of only those players who are under 25 years old and have a batting average of .280 or better, then display them in order of age.
My code, shown below, is working perfectly until option 2 is selected. It is not sorting or showing anything. If someone could help me out it would mean so much. Any overall suggestions about my code will also be really helpful.Thank you.
import java.io.*;
import java.util.Scanner;
public class BlueJays {
static String name[] = new String[3]; //Name Array that can hold 10 names
static int age[] = new int[3]; //Age Array that can hold 10 ages
static String position[] = new String[3]; //Position Array that can hold 10 positions
static double average[] = new double[3]; //Average Array the can hold 10 batting averages
static int x, i;
//Main Method
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int menuChoice = 1;
System.out.print("Hello and Wlecome to Blue Jay Java Sort");
while (menuChoice != 3) {
System.out.print("\rEnter Menu Choice\n");
System.out.print("**********************");
System.out.print("\r(1) => Enter Blue Jay Data \n");
System.out.print("(2) => Display Possible Draft Choices \n");
System.out.print("(3) => Exit \r");
//try-catch statement for each case scenario
try {
menuChoice = Integer.parseInt(br.readLine());
} catch (IOException ie) {
ie.printStackTrace();
}
switch(menuChoice) {
case 1:
inputInfo();
break;
case 2:
inputSort();
break;
case 3:
return;
}
}
}
public static void inputInfo() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner p = new Scanner(System.in);
//loop to request to fill array
for (x = 0; x < 3; x++) {
//Ask for player name
System.out.print("\rEnter player full name: ");
//Read input and store name in an Array
name[x] = in.readLine();
//Ask for player age
System.out.print("Enter age of player: ");
//Read input and store age in an Array
age[x] = p.nextInt();
//Ask for position of player
System.out.print("Enter player position: ");
//Read input and store position in an Array
position[x] = in.readLine();
//Ask for batting average of player
System.out.print("Enter batting average of player: ");
//Read input and store batting average in an Array
average[x] = p.nextDouble();
}
}
public static void inputSort() {
int smallest, temp;
//Selection Sort
for (x = 0; x < 3 - 1; ++x) {
smallest = x;
for(i = x + 1; i < 10; ++i) {
if (age[i] < age [smallest]) {
smallest = i;
}
}
temp = age [x];
age [x] = age [smallest];
age [smallest] = temp;
}
System.out.println(" Name " + " -----" + " Age " + "-----" + " Position " + "-----" + "Batting Average ");
for (x = 0 ; x < 3; x++) {
if (age[x] <= 25 && average[x] >= .280) {
System.out.println( name[x] + " ----- " + age[x] + " ----- " + position[x] + " ----- " + average[x]);
}
}
//Close Main()
}
//Close Class
}
`
Modificaton:
Here you need to make a small change in your program as shown below:
In inputSort() method, You need to change your for loop condition from for(i = x + 1; i < 10; ++i) to for(i = x + 1; i < 3; ++i).
You must be getting an error stating ArrayIndexOutOfBound because you were trying to access an index value that does not exist.
public class BlueJays {
static String name[] = new String[3]; //Name Array that can hold 10 names
static int age[] = new int[3]; //Age Array that can hold 10 ages
static String position[] = new String[3]; //Position Array that can hold 10 positions
static double average[] = new double[3]; //Average Array the can hold 10 batting averages
static int x, i;
//Main Method
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int menuChoice = 1;
System.out.print("Hello and Wlecome to Blue Jay Java Sort");
while (menuChoice != 3) {
System.out.print("\rEnter Menu Choice\n");
System.out.print("**********************");
System.out.print("\r(1) => Enter Blue Jay Data \n");
System.out.print("(2) => Display Possible Draft Choices \n");
System.out.print("(3) => Exit \r");
//try-catch statement for each case scenario
try {
menuChoice = Integer.parseInt(br.readLine());
} catch (IOException ie) {
ie.printStackTrace();
}
switch(menuChoice) {
case 1:
inputInfo();
break;
case 2:
inputSort();
break;
case 3:
return;
}
}
}
public static void inputInfo() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner p = new Scanner(System.in);
//loop to request to fill array
for (x = 0; x < 3; x++) {
//Ask for player name
System.out.print("\rEnter player full name: ");
//Read input and store name in an Array
name[x] = in.readLine();
//Ask for player age
System.out.print("Enter age of player: ");
//Read input and store age in an Array
age[x] = p.nextInt();
//Ask for position of player
System.out.print("Enter player position: ");
//Read input and store position in an Array
position[x] = in.readLine();
//Ask for batting average of player
System.out.print("Enter batting average of player: ");
//Read input and store batting average in an Array
average[x] = p.nextDouble();
}
}
public static void inputSort() {
int smallest, temp;
//Selection Sort
for (x = 0; x < 3 - 1; ++x) {
smallest = x;
for(i = x + 1; i < 3; ++i) {
if (age[i] < age[smallest]) {
smallest = i;
}
}
temp = age [x];
age [x] = age [smallest];
age [smallest] = temp;
}
System.out.println(" Name " + " -----" + " Age " + "-----" + " Position " + "-----" + "Batting Average ");
for (x = 0 ; x < 3; x++) {
if (age[x] <= 25 && average[x] >= .280) {
System.out.println( name[x] + " ----- " + age[x] + " ----- " + position[x] + " ----- " + average[x]);
}
}
//Close Main()
}
}
I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}
I've been working on this program for 20+ hours and I feel like I'm really close to finishing, but I cannot seem to fix my array out of bounds exception. I'll provide my whole code here:
import java.util.Scanner;
import java.util.ArrayList;
public class GradeCalcArryas { /*
* Logan Wegner The purpose is to calculate
* entered grades
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // first scanner for inputs
Scanner s1 = new Scanner(System.in); // second scanner for string
boolean done = false; // so an if statement can be inputted for the code
// to break back to the menu
boolean quit = false;
int choice = 0;
final int MAX_STUDENTS = 200;
//Array created to store the information entered for exams
int[] examStats = new int[3];
//Array created to store the information entered for quizzes
int[] quizStats = new int[3];
//Array created to store the information entered for homework
int[] homeworkStats = new int[3];
//Array created to store the student name information entered
String[] studentNames = new String[MAX_STUDENTS];
System.out.println("Welcome to GradeBook!");
System.out.println("Please provide grade item details");
System.out.print("Exams (number, points, weight):");
examStats[0] = s.nextInt(); // inputs exam number
examStats[1] = s.nextInt(); // inputs exam points
examStats[2] = s.nextInt(); // inputs exam weight
System.out.print("Quizzes (number, points, weight):");
quizStats[0] = s.nextInt(); // inputs quiz number
quizStats[1] = s.nextInt(); // inputs quiz points
quizStats[2] = s.nextInt(); // inputs quiz weight
System.out.print("Homework (number, points, weight):");
homeworkStats[0] = s.nextInt(); // inputs homework number
homeworkStats[1] = s.nextInt(); // inputs homework points
homeworkStats[2] = s.nextInt(); // inputs homework weight
/*int numExams = examStats[0];
int numQuizzes = quizStats[0];
int numHW = homeworkStats[0];
int tableLength = numExams + numQuizzes + numHW + 1;*/
/*double[][] examScores = new double[MAX_STUDENTS][];
double[][] quizScores = new double[MAX_STUDENTS][];
double[][] hwScores = new double[MAX_STUDENTS][];*/
//arrays for the average exam, quiz, homework, gradeAverage, and gradeWeightedAverage score of each student
double[] examAverage = new double[MAX_STUDENTS];
double[] quizAverage = new double[MAX_STUDENTS];
double[] hwAverage = new double[MAX_STUDENTS];
double[] gradeAverage = new double[MAX_STUDENTS];
// counters
int numExams = 0;
int numQuizzes = 0;
int numHW = 0;
// declare Double[] exams using length numExams
double[] exams = new double[numExams];
// declare Double[] quizzes using length numQuizzes
double[] quizzes = new double[numQuizzes];
// declare Double[] HW using length numHW
double[] hw = new double[numHW];
//Calculating percentage to multiply exam, quiz, and homework averages
double examWeight = examStats[2]/100;
double quizWeight = quizStats[2]/100;
double hwWeight = homeworkStats[2]/100;
System.out.println("--------------------");
do {
System.out.println("What would you like to do?");
System.out.println(" 1 Add student data");
System.out.println(" 2 Display student grades & statistics");
System.out.println(" 3 Plot grade distribution");
System.out.println(" 4 Quit");
System.out.print("Your choice:");
choice = s.nextInt(); /*
* Choice will determine what the next course of
* action will be with the program
*/
if (choice == 1) { // ADD STUDENT DATA
System.out.println("Enter student data:");
for (int i = 0; i <= MAX_STUDENTS; i++) { // iterate through 200
// times
// (MAX_STUDENTS) or
// break
System.out.print("Data>");
String dataentry = s1.nextLine(); // read inputed data
if (dataentry.equals("done")) { // if user inputs "done",
// break
break;
}
// ArrayList that holds all information (Name, Exams,
// Quizzes, Homework)
ArrayList<String> allInfo = new ArrayList<String>();
// tokenize using ":" delimiter, splitting up the name
// (firstsplit[0]) from the rest of the information
String[] firstsplit = dataentry.split(":");
studentNames[i] = firstsplit[0];
// add name to ArrayList allinfo
allInfo.add(firstsplit[0] + "\t");
// tokenize using " " delimiter, splitting up each score
String[] secondsplit = firstsplit[1].split(" ");
for (int k = 0; k < secondsplit.length; k++) { // iterates
// through
// Array
// secondsplit
allInfo.add(secondsplit[k] + "\t"); // adds item at [k]
// to ArrayList
// allInfo
// if the first char in secondsplit[k] is "e" increment
// numExams
if (secondsplit[k].subSequence(0, 1).equals("e"))
numExams++;
// if the first char in secondsplit[k] is "q" increment
// numQuizzes
if (secondsplit[k].subSequence(0, 1).equals("q"))
numQuizzes++;
// if the first char in secondsplit[k] is "h" increment
// numHW
if (secondsplit[k].subSequence(0, 1).equals("h"))
numHW++;
}
// iterates through Array exams and adds values from allInfo
for (int k = 0; k < exams.length; k++) {
exams[k] = Double.parseDouble(allInfo.get(1 + k)
.substring(1));
}
// iterates through Array quizzes and adds values from
// allInfo
for (int k = 0; k < quizzes.length; k++) {
quizzes[k] = Double.parseDouble(allInfo.get(
1 + numExams + k).substring(1));
}
// iterates through Array hw and adds values from allInfo
for (int k = 0; k < hw.length; k++) {
hw[k] = Double.parseDouble(allInfo.get(
1 + numExams + numQuizzes + k).substring(1));
}
//Index counters for averages
int examIndex = 0;
int quizIndex = 0;
int hwIndex = 0;
int gradeAveragingIndex = 0;
//loop finding the gradeAverage
for(int index = 0; index < MAX_STUDENTS; index++){
examAverage[index] = ((exams[examIndex]) + (exams[examIndex+1]) + (exams[examIndex+2])) / (numExams);
quizAverage[index] = ((quizzes[quizIndex]) + (quizzes[quizIndex+1]) + (quizzes[quizIndex+2])) / (numQuizzes);
hwAverage[index] = ((hw[hwIndex]) + (hw[hwIndex+1]) + (hw[hwIndex+2])) / (numHW);
gradeAverage[index] = ((examAverage[gradeAveragingIndex] * examWeight) + (quizAverage[gradeAveragingIndex] * quizWeight) + (hwAverage[gradeAveragingIndex] * hwWeight) / numExams);
examIndex+=3;
quizIndex+=3;
hwIndex+=3;
gradeAveragingIndex++;
}
}
}
//This choice is to display student grades & statistics in a table
if (choice == 2) {
System.out.println("Display student grades & statistics");
//Formatting for the heading of my grade table
System.out.printf("%-10s","Name");
System.out.printf("%-5s","Exam");
System.out.printf("%-5s","Exam");
System.out.printf("%-5s","Exam");
System.out.printf("%-5s","Quiz");
System.out.printf("%-5s","Quiz");
System.out.printf("%-5s","Quiz");
System.out.printf("%-7s","HWork");
System.out.printf("%-7s","HWork");
System.out.printf("%-7s","HWork");
System.out.printf("%-5s","Grade\n");
//declaring index counters
int studentNameIndex = 0;
int examGradeIndex = 0;
int quizGradeIndex = 0;
int homeworkGradeIndex = 0;
int gradeAverageIndex = 0;
//for loop for the output of exams, quizzes, homework, and grade average
for(int index = 0; index < studentNames.length; index++) {
System.out.printf("%-10s",studentNames[studentNameIndex]);
System.out.printf("%-5.1f",exams[examGradeIndex]);
System.out.printf("%-5.1f",exams[examGradeIndex+1]);
System.out.printf("%-5.1f",exams[examGradeIndex+2]);
System.out.printf("%-5.1f",quizzes[quizGradeIndex]);
System.out.printf("%-5.1f",quizzes[quizGradeIndex+1]);
System.out.printf("%-5.1f",quizzes[quizGradeIndex+2]);
System.out.printf("%-7.1f",hw[homeworkGradeIndex]);
System.out.printf("%-7.1f",hw[homeworkGradeIndex+1]);
System.out.printf("%-7.1f",hw[homeworkGradeIndex+2]);
System.out.printf("%-5.1f",gradeAverage[gradeAverageIndex] + "\n");
studentNameIndex++;
examGradeIndex+=3;
quizGradeIndex+=3;
homeworkGradeIndex+=3;
gradeAverageIndex++;
}
}
if (choice == 3) {
}
if (choice == 4) {
quit = true;
System.out.println("Good bye!");
}
}while (quit == false);
}
}
My out of bounds exception occurs here:
//loop finding the gradeAverage
for(int index = 0; index < MAX_STUDENTS; index++){
examAverage[index] = ((exams[examIndex]) + (exams[examIndex+1]) + (exams[examIndex+2])) / (numExams);
quizAverage[index] = ((quizzes[quizIndex]) + (quizzes[quizIndex+1]) + (quizzes[quizIndex+2])) / (numQuizzes);
hwAverage[index] = ((hw[hwIndex]) + (hw[hwIndex+1]) + (hw[hwIndex+2])) / (numHW);
gradeAverage[index] = ((examAverage[gradeAveragingIndex] * examWeight) + (quizAverage[gradeAveragingIndex] * quizWeight) + (hwAverage[gradeAveragingIndex] * hwWeight) / numExams);
examIndex+=3;
quizIndex+=3;
hwIndex+=3;
gradeAveragingIndex++;
}
My exception is either ArrayOutofBounds: 0 or ArrayOutofBounds: 3. It has something to do with my exam, quiz, and hw arrays. I've moved them around in my program and changed my numExams, numQuizzes, and numHW values, but it still gives me some trouble. I'd love some insight. Thanks in advance guys.
For sure you have issue here:
int numExams = 0;
int numQuizzes = 0;
int numHW = 0;
// declare Double[] exams using length numExams
double[] exams = new double[numExams];
// declare Double[] quizzes using length numQuizzes
double[] quizzes = new double[numQuizzes];
// declare Double[] HW using length numHW
double[] hw = new double[numHW];
Your are declaring here arrays with size 0. If you have more issues - I was not checking.