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.
Related
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));
}
}
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()
}
}
Idea:
User inputs their bets by typing either 'W','L' or 'T' (wins, losses or tie). Program generates random results within these parameters. User input and result gets printed, and a score is presented based on correct bets, which is supplied by the program.
Im having issues on how to proceed with comparing user generated input from scanner to an arraylist that produces a random result.
If it were not for the multiple "questions" and "answers" I could use a (val.equals(input)) of sort. However, each individual bet is random and must be matched against the users bets to sum up the users score, that complicates it.
Any help appreciated.
public class test3 {
public static void main(String[] args) {
int score = 0;
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
test3 obj = new test3();
for(int i = 0; i < 5; i++){
System.out.print(obj.getRandomList(list) + " ");
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private Random random = new Random();
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
One way to do this is in the code below.
You basically need to compare each element of your input with each element of the random list so run loop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Test {
private Random random = new Random();
public static void main(String[] args) {
int score = 0;
System.out
.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++) {
System.out.println("Please enter your bet:");
array[i] = input.nextLine();
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++) {
System.out.print(array[i] + " ");
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
Test obj = new Test();
List<String> randList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
randList.add(obj.getRandomList(list));
}
for(String randBet : randList){
System.out.print( randBet + " ");
}
System.out.println("");
int counter = 0;
for (String yourbet: Arrays.asList(array)){
if(randList.get(counter).equals(yourbet)){
score++;
}
counter++;
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
I removed test3 for simplicity, but basically you need save results on array and generate random results and saving them (i.e a list). Then you have to iterate through and compare each game result, and if your bet is correct, just add one to score. Check the code below:
Main:
public static void main(String[] args) {
int score = 0;
String array[] = new String[5];
List < String > randomResultList = new ArrayList<String> ( );
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
for(int i = 0; i < 5; i++){
String randomResult = getRandomList();
System.out.print( randomResult + " ");
randomResultList.add ( randomResult );
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
//here is where you compare each result
for(int i = 0; i < 5; i++)
{
if( array[i].equals ( randomResultList.get ( i ) ))
{
score++;
}
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private static Random random = new Random();
public static String getRandomList() {
List<String> list = Arrays.asList("w", "l", "t");
int index = random.nextInt(list.size());
return list.get(index);
}
I/O Example:
Betting game initiating...
Type 'W' for win, 'L' for loss and 'T' for tie.
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
This week wins, losses and ties loading...
Result:
l l l t w
Your bets were:
w w w w w
You were correct on: 1 bettings
Extra:
You could do all on the same iteration! check this out.
public static void main(String[] args) {
int score = 0;
// Win Loose or Tie
List<String> list = Arrays.asList("w", "l", "t");
Random rand = new Random ( );
//String with result and bets i.e (wwwww) and (wlltw). This avoid another iteration.
String result="";
String bets = "";
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
String bet =input.nextLine();
String randomResult = ( list.get ( rand.nextInt ( list.size ( ) ) ));
//concatenate String with results and bets with +=
result += randomResult;
bets += bet;
//check if u won
if( bet.equals ( randomResult ))
{
score++;
}
}
//This are just the results! no more iterations.
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:" + result);
System.out.println("\n\nYour bets were:" + bets );
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
So I am creating an invoice program and I got stuck at the part when I have to get the total I got from multiplying two arrays. I am able to multiply them and I get the values but unfortunately more than one value if I enter more than one item. I want to be able to add the values I get to get a total.
To give you an idea, here's my code:
public static void main(String []args){
Scanner input = new Scanner(System.in);
String sentinel = "End";
String description[] = new String[100];
int quantity[] = new int[100];
double price [] = new double[100];
int i = 0;
// do loop to get input from user until user enters sentinel to terminate data entry
do
{
System.out.println("Enter the Product Description or " + sentinel + " to stop");
description[i] = input.next();
// If user input is not the sentinal then get the quantity and price and increase the index
if (!(description[i].equalsIgnoreCase(sentinel))) {
System.out.println("Enter the Quantity");
quantity[i] = input.nextInt();
System.out.println("Enter the Product Price ");
price[i] = input.nextDouble();
}
i++;
} while (!(description[i-1].equalsIgnoreCase(sentinel)));
System.out.println("Item Description: ");
System.out.println("-------------------");
for(int a = 0; a <description.length; a++){
if(description[a]!=null){
System.out.println(description[a]);
}
}
System.out.println("-------------------\n");
System.out.println("Quantity:");
System.out.println("-------------------");
for(int b = 0; b <quantity.length; b++){
if(quantity[b]!=0){
System.out.println(quantity[b]);
}
}
System.out.println("-------------------\n");
System.out.println("Price:");
System.out.println("-------------------");
for(int c = 0; c <price.length; c++){
if(price[c]!=0){
System.out.println("$"+price[c]);
}
}
System.out.println("-------------------");
//THIS IS WHERE I MULTIPLY THE PRICE AND THE QUANTIY TOGETHER TO GET THE TOTAL
for (int j = 0; j < quantity.length; j++)
{
//double total;
double total;
total = quantity[j] * price[j];
if(total != 0){
System.out.println("Total: " + total);
}
}
}
}
In your last for loop, you're only multiplying the quantity and the price of the item and putting it as the value of total instead of adding it to total. Also every time it loops it creates a new total.To make it better, declare total out of the loop and move your if statement out
double total = 0.0;
for (int j = 0; j < quantity.length; j++){
total += quantity[j] * price[j];
}
if(total != 0){
System.out.println("Total: " + total);
}
I need to create a 2d array which can read in the student ID's of 50 students and each of their 7 subject marks. I have come up with a way to store subject marks but not sure how to store the student ID's.
Here is the code so far.
public static void main(String[] args)
{
double mark;
double[][] studs = new double[50][7];
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 3; studentNo++) {
System.out.println("enter student ID number for student " + studentNo);
for (int moduleNo = 0; moduleNo < 2; moduleNo++) {
System.out.println("Enter users mark for module " + moduleNo);
mark = fromKeyboard.nextDouble();
studs[studentNo][moduleNo] = mark;
}
}
}
You have only one array of a single primitive type, but you have two pieces of information.
Two simple options are
1) Use another array to store the IDs
2) (Better solution IMO) Create your own Student class, and define an array Student[] (A student should contain a field for an array of marks)
You can use array[n][0] to store student id.
This should work:
public static void main(String[] args)
{
double mark = 0d;
int id = 0;
double[][] studs = new double[50][8];
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 50; studentNo++) {
System.out.print("enter student ID number for student " + (studentNo + 1) + ":");
id = fromKeyboard.nextInt();
studs[studentNo][0] = id;
for (int moduleNo = 1; moduleNo < 8; moduleNo++) {
System.out.print("Enter mark of student " + id + " for module " + moduleNo);
mark = fromKeyboard.nextDouble();
studs[studentNo][moduleNo] = mark;
}
}
fromKeyboard.close();
}
NOTES:
If you cannot modify the original array or you need to store students name, for example, you can create a new array to store students id like.
String[] studentsId = new String[50];
int[] studentsId = new int[50];
remember to close resources when using it: fromKeyboard.close();
When I understood your question correct:
public static void main(String[] args)
{
double[][] studs = new double[50][8];
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 50; studentNo++) {
System.out.println("enter student ID number for student " + studentNo);
studs[studentNo][0] = fromKeyboard.nextDouble(); //save id
for (int moduleNo = 1; moduleNo < 8; moduleNo++) {
System.out.println("Enter users mark for module " + moduleNo);
studs[studentNo][moduleNo] = fromKeyboard.nextDouble(); // your 7 marks
}
}
}
You're on the right track.
You aren't reading the studentNo input. So you need to read that and place it in the first cell before the inner loop. Then put all the marks on the same row along side it. This is depending on the type of student ID, is it a String or number?
Also, why have 7 columns in the array and only loop twice for subject grades? Is there more to do here. If not avoid using up the space.