Trouble splitting data in Java program - java

I'm trying to split my variables and enter my student data in so I can move on with my grade calculation program, but my second time splitting the entered string, there is a problem and I cannot figure out what is the cause of it.
Users will enter information in that looks like this
John Denver: e100 q70 q50 h100 e100 e90 h80 q60 h100
The program needs to split apart all of this data and get the name entered into an array, and then the exam scores, quiz scores and homework scores represented by the "e", "q" or "h" in the entered data.
import java.util.Scanner;
public class GradeCalcWithArrays { /*
* Daniel The purpose is to calculate
* entered grades
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean done = false;
boolean quit = false;
int choice = 0;
int maxstudents = 200;
int[] examstats = new int[3]; /*
* Array created to store the information
* entered for exams
*/
int[] quizstats = new int[3]; /*
* Array created to store the information
* entered for quizzes
*/
int[] homeworkstats = new int[3]; /*
* Array created to store the
* information entered for homework
*/
String[] studentnames = new String[maxstudents]; /*
* Array created to
* store the student
* name information
* entered
*/
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
double[] examscores = new double[examstats[0]];
double[] quizscores = new double[quizstats[0]];
double[] hwscores = new double[homeworkstats[0]];
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) {
System.out.println("Enter student data:");
for (int i = 0; i <= maxstudents; i++) {
System.out.print("Data>");
String dataentry = s.nextLine();
String[] firstsplit = dataentry.split(":");
studentnames[i] = firstsplit[0];
String[] secondsplit = firstsplit[1].split(" ");
for (int j = 0; j <= maxstudents; j++) {
String c;
c = secondsplit[j].substring(0, 1);
if (c == "e") {
secondsplit = secondsplit[j].split("e");
examscores[i] = Double.parseDouble(secondsplit[j]);
}
if (c == "q") {
secondsplit = secondsplit[j].split("q");
quizscores[i] = Double.parseDouble(secondsplit[j]);
}
if (c == "h") {
secondsplit = secondsplit[j].split("h");
hwscores[i] = Double.parseDouble(secondsplit[j]);
}
if (dataentry.equals("done")) {
break;
}
}
}
}
if (choice == 2) {
}
if (choice == 3) {
}
if (choice == 4) {
quit = true;
System.out.println("Good bye!");
}
} while (quit == false);
}
}
I get an error that says: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GradeCalcWithArrays.main(GradeCalcWithArrays.java:83)
Can someone help me fix this and tell me if my program is going to work?

One thing that is wrong is that you have maxstudents set to 200, you allocate the studentnames array with size 200, but that means that the valid subscripts are 0 through 199, but your for loop uses a less than or equal test against 200:
`for (int i = 0; i <= maxstudents; i++)`
That means that i is 200 on the last iteration, so in that iteration your code will effectively execute studentnames[200] = firstsplit[0]; and that will cause an ArrayIndexOutOfBoundsException.
The above, however, will be a problem if you reach the 200th iteration without breaking out of the for loop. Looking at the code, I do see that you are attempting to break if the input is "done", however that break statement is actually inside the nested for loop, so it does not break out of the outer loop. That test really should happen before you do the first split. There's no reason to even try to split if the input was "done", so also no reason to go into the nested for loop.
There are additional problems as well: The nested for loop should not be testing against maxstudents because it's the number of grades that you care about. I'll leave the rest of them for you to figure out - with a hint about one of them: you should be checking your input for errors.

Related

Java - Cannot get loop to recognize newly generated array values

I am creating a program for class where I can bet on a horse race. The winners are determined by a method given to us by our professor. here is the method:
void readySetGo() {
System.out.println(array.length);
int length = array.length;
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomValue = i + rgen.nextInt(length - i);
int randomElement = array[randomValue];
array[randomValue] = array[i];
array[i] = randomElement;
}
}
I created a string-based menu using a while loop. In order to make things easier on myself, I created a cheat box that displays the winners before you place your bet.
System.out.print("Cheat: ");
System.out.println(Arrays.toString(racer.getArray()));
Here is the main method:
public static void main(String[] args) {
race racer = new race();
wallet balance = new wallet();
Scanner input = new Scanner(System.in);
double pick1;
double pick2;
String response;
balance.setUSDbalance(200);
racer.readySetGo();
System.out.print("Cheat: ");
System.out.println(Arrays.toString(racer.getArray()));
System.out.println("Welcome to Charlie's Horse Racing Bets!");
System.out.println("\nType one of the strings below and add your horse numbers after:");
System.out.println("Example: 'Exacta Box 2 3'");
System.out.println("\n=> Exacta");
System.out.print("\nEnter your choice: ");
response = input.nextLine();
String words[] = response.split(" ");
while (true) {
if (words[0].equalsIgnoreCase("Exit")) {
System.out.println("Thanks for playing! \nSee you soon!");
} else if (words[0].equalsIgnoreCase("Exacta")) {
pick1 = Double.parseDouble(words[1]);
pick2 = Double.parseDouble(words[2]);
boolean way1 = (pick1 == racer.first()) && (pick2 == racer.second());
boolean way2 = (pick1 == racer.second()) && (pick2 == racer.first());
if (way1 || way2) {
System.out.println("You won the exact box");
System.out.print("The winning order was: ");
System.out.println(Arrays.toString(racer.getArray()));
System.out.print("\nCheat for next round: ");
racer.readySetGo();
System.out.println(Arrays.toString(racer.getArray()));
System.out.print("\nEnter your new choice: ");
response = input.nextLine();
} else {
System.out.println("You chose the wrong order. Play again?");
System.out.print("\nEnter your new choice: ");
response = input.nextLine();
}
}
}
}
The problem is that the system recognizes the correct user input the first time, but doesn't work at all the second time. Example:
Cheat: [4, 1, 3, 2]
Welcome to Charlie's Horse Racing Bets!
Type one of the strings below and add your horse numbers after:
Example: 'Exacta Box 2 3'
=> Exacta
Enter your choice: exacta 4 1
You won the exact box
The winning order was: [4, 1, 3, 2]
Cheat for next round: [3, 1, 4, 2]
Enter your new choice: exacta 3 1
You chose the wrong order. Play again?
As your code currently stands, you're only parsing the user's input the first time. Inside the loop you're reading the user's input again, but you're not updating the words variable based on the new input.
You should move this line inside your loop:
String words[] = response.split(" ");

Replacing Position in Array Amongst Other Methods

Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.
I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

How do you use a method to calculate 1 array parameter of grades and returns the total of the array?

My schoolwork is asking me to write a Java program. I'm not getting something quite right.
Basically I have to create a Java method that gets a user to enter x amount of grades (users choice), store the grades in an array and then add the grades in the array up to be called in the main method.
Here's my code:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int [] storeGrades = new int[numberOfGrades];
}
public static int getTotalScore(int numberOfGrades[]) {
Scanner keyboard = new Scanner(System.in);
int getTotalScore;
int []storeGrades;
for (int i = 0; i < getTotalScore; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
int userGradeNumbers = keyboard.nextInt();
storeGrades[i] = userGradeNumbers;
sum += userGradeNumbers;
}
}
}
I'm getting an error at "sum" that it hasn't been resolved to a variable? It won't let me initialize sum within the for loop, nor the getTotalScore method. Why not?
First, get the grades. Then call the method to get the sum. Declare the sum and initialize it to 0 before your loop. Return it after. Like,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println(getTotalScore(storeGrades));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
Your code has the right intent about it, but some of the ordering of things is a little off and there are syntactical issues at the moment.
I would advocate splitting up your code into two methods (unless you're specifically prohibited from doing so based on the assignment). One method to get the grades from the user, and another to sum the grades. The reason for this, is that you end up trying to both store and sum the grades at the same time (which is technically more efficient), but that doesn't teach you how to calculate a running total by iterating over an array (which is likely the point of the lesson).
One other thing that I would call out (which may be beyond where you are in the course right now), is that when you're using a Scanner, you need to validate that the user has typed what you think they've typed. It's entirely plausible that you want the user to type a number, and they type "Avocado." Because Java is strongly typed, this will cause your program to throw an exception and crash. I've added in some basic input validations as an example of how you can do this; the general idea is:
1) Check that the Scanner has an int
2) If it doesn't have an int, ask the user to try again
3) Else, it has an int and you're good to proceed. Store the value.
One last thing about Scanners. Remember to close them! If you don't, you can end up with a memory leak as the Scanner continues to run.
Below is how I would have revised your code to do what you want. Shoot me a comment if something doesn't make sense, and I'll explain further. I left comments inline, as I figured that was easier to digest!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* #param numberOfGrades the total number of grades that will be requested from the user.
* #param keyboard the scanner that the user will use to provide the grades.
* #return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* #param storedGrades the grades to be summed.
* #return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}

Array not capturing first user entry

I am attempting to fill an array with floating point numbers using a method. Every time I run my program it does not capture the first number entered.
How can I correct my code so it captures the first user input?
Thanks!
public static void main(String[] args)
{
//Read user input into the array
final int INITIAL_SIZE = 8;
double[] inputs = new double[INITIAL_SIZE];
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of credits for a course, Q to quit:");
double credits = in.nextDouble();
int currentSize = 0;
while (in.hasNextDouble())
{
if (credits <= 0)
{
System.out.println("All entries must be a positive number.");
}
else
{
// Grow the array if it has been completely filled
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
}
System.out.println(Arrays.toString(inputs));
}
Prolem is You did not store first user entry, so it's not showing to you
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of credits for a course, Q to quit:");
--> double credits = in.nextDouble();
You have taken the value from user but did not stored it in inputs
If you want to take value of credit from user and want to store credit in inputs then you should do:
double credits = in.nextDouble();
inputs[0] = credits ;
int currentSize = 1;
The problem might be in this line : inputs[currentSize] = in.nextDouble();
You are storing the first value in credits but not assigning it to inputs array.

Categories

Resources