java.lang.ArrayIndexOutOfBoundsException? - java

I am currently teaching my self some basic Java through a text book and gave myself a "homework problem" but I'm having difficulty when writing to a .txt file of a method. It doesn't want to take more than 2 people. Here's a quick run down of what the method is meant to do:
1.) Collects the number of people the user would like to enter into the data file
2.) Collects the first and last name of each person in a two-dimensional array
3.) Collects a number of payments set by the user for each (separate) person that the user entered into an array.
4.) Then it calculates the average payment for each of the people entered into another array(so each person should have their own average)
5.) Lastly, it writes the data to a .txt file named "BusinessData.txt."
It seems to be working perfectly up until it tries to write more than 2 people into the .txt file. It's driving me nuts and I really would like to know how to fix this before moving on to the next couple of topics.
Here's the error message that I am getting when I try to add more than 2 people:
Exception in thread "main" java.lang.Array IndexOutofBoundsException:
3
at Business1.dataCollect(Business1.java:210)
at Business1.main(Business1.java:62)
I'd greatly appreciate any tips.
Here's the actual code:
import java.util.*;
import java.io.*;
public class Business1
{
public static void main(String[] args) throws IOException
{
// Declare local variables
int menuChoice;
// Declare local objects
Scanner input = new Scanner(System.in);
// Display the program title
System.out.println("\n\n\n\n\t\t\t\t***************************************\n"
+ "\t\t\t\t* Average Customer Payment Calculator *\n"
+ "\t\t\t\t***************************************\n\n\n");
// Start of a do-while loop: Continues the program as long as the user doesn't choose to exit
do
{
// Start of a do-while loop: Input Validation (menuChoice must be between 1 - 4)
do
{
// Prompt user for menuChoice
System.out.print("\tPlease enter an integer in accordance to the given choices:\n\n"
+ "\t(1) Collect and Erase Old Data\n"
+ "\t(2) Read Saved Data\n"
+ "\t(3) Append Old Data\n"
+ "\t(4) Exit Program\n\n"
+"\tEnter Choice: ");
menuChoice = input.nextInt();
System.out.println("\n\n");
// If menuChoice is equal to 1: Erase old Data and Collect and Write new data
if(menuChoice == 1)
{
try
{
dataCollect();
}
catch(IOException e)
{
System.out.println("Error");
}
}
// else if menuChoice is equal to 2: Read Saved Data
else if(menuChoice == 2)
{
}
// else if menuChoice is equal to 3: Append Old Data
else if(menuChoice == 3)
{
}
// else if menuChoice is equal to 4: Exit Program
else if(menuChoice == 4)
{
System.out.println("\n\n\n\t\tGoodbye!\n\n\n");
}
// else display error message: Error. Please enter a number 1 - 4
else
{
System.out.println("\n\nERROR. Please enter a number 1 - 4\n\n");
}
// End of do-while loop: Input Validation (menuChoice must be between 1 - 4)
} while(menuChoice < 1 || menuChoice > 4);
// End of a do-while loop: Continues the program as long as the user doesn't choose to exit
} while(menuChoice != 4);
}
// Create a method named dataCollect
public static void dataCollect() throws IOException
{
// Declare local variables
int numPeople, numPayments /* array size for payments */;
double totalPayments = 0, averagePayment;
double [] paymentsArray /* different payments */, averagePaymentsArray;
String [][] namesArray /* First name, last name in array */;
// Declare objects
Scanner keyboard = new Scanner(System.in);
// Prompt user for the number of people they would like to add to the records and store in variable numPeople
System.out.print("\tHow many people would you like to add to your records?\n\n\tEnter an integer: ");
numPeople = keyboard.nextInt();
System.out.println("\n\n");
// Initialize arrays
namesArray = new String[numPeople][2];
// Create a counter for the for-loop
int count = 0;
// For-loop will prompt user for first and last name of each person
for(int i = 1; i <= numPeople; i++)
{
// Consume the remaining newline character
keyboard.nextLine();
// Prompt user for first name
System.out.print("\tPlease enter the FIRST name of person #" + i +": ");
namesArray[count][0] = keyboard.nextLine();
System.out.println("\n\n");
//Prompt user for last name
System.out.print("\tPlease enter the LAST name of person #" + i + ": ");
namesArray[count][1] = keyboard.nextLine();
System.out.println("\n\n\n");
count++;
}
// Reset counter for the next for-loop
count = 0;
int count2 = 1; // Used to keep track of which payment number the user is inputing
int count3 = 0;
int count4 = -1;
// ****************************************************************
// * Open file for input ******************************************
// ****************************************************************
PrintWriter outputFile = new PrintWriter("BusinessData.txt");
outputFile.println("\t\t\tBusiness Data\n\n");
outputFile.println("First Name\tLast Name\tP 1\t\tP 2\t\t P 3\t\tAverage Payments\n\n"
+ "------------------------------------------------------------------------------------------------------------------------------------------------------\n");
// For-loop will ask for number of payments each person made while also collecting the value of each of those payments in a nested for-loop.
for(int i = 0; i < numPeople; i++)
{
// Prompt user for first name
System.out.print("\tPlease enter the number of payments made by " + namesArray[count][0] +" " + namesArray[count][1] + "(Put in 3 for now) : ");
numPayments = keyboard.nextInt();
System.out.println("\n\n");
// Initialize array then reset it for the next person to come
paymentsArray = new double[numPayments];
for(int j = 0; j < numPayments; j++)
{
// ****************************************************************
// * Open file for input ******************************************
// ****************************************************************
System.out.print("\n\n\tPlease enter payment value of payment #" + count2 + " that " + namesArray[count][0] +" " + namesArray[count][1] + " made: $");
paymentsArray[j] = keyboard.nextDouble();
System.out.println("\n\n");
// Increment counter
count2++;
}
// ************************************************************************
// * Calculating Average Payment ******************************************
// ************************************************************************
// For loop for calculating average
for(int k = 0; k < numPayments; k++)
{
totalPayments += paymentsArray[k];
}
// Calculate the Average Payment
averagePayment = totalPayments/paymentsArray.length;
/**************************************************
********** BUG LIES IN THE WRITING **************
***************************************************/
// nested for-loop will write data now otherwise it'll just be wiped out and overwritten by the next input
for(int l = 1; l < numPeople; l++)
{
// Increment counter4
count4++;
// Output first name
outputFile.print(namesArray[count4][count3]);
// Increment counter3
count3++;
// Output last name
outputFile.print("\t\t" + namesArray[count4][count3] + "\t\t");
// Reset counter3
count3 = 0;
for (int m = 0; m < numPayments; m++)
{
outputFile.print(paymentsArray[m] + "\t\t");
}
outputFile.println(averagePayment + "\n\n");
}
// Reset total Payments for the next iteration
totalPayments = 0.0;
// Increment the counter
count++;
}
outputFile.close();
// End of dataCollect method
}

Running your code gives me Exception for 3+ users.
ArrayIndexOutOfBoundsException thrown at
outputFile.print(namesArray[count4][count3]);
Running in debug mode shows that namesArray[count4][count3] is pointing to a value which is not available .
count4 is incremented to out of bounds value because of the below loop.
I don't undertstand why you need this loop
for(int l = 1; l < numPeople; l++)
{
enter code here}
If you remove this it works fine.

Related

Proper placing of the myScanner.next() method using Scanner class

Question 2:
As the code is written, if the use inputs a valid integer it asks for "Enter number 2", then "Enter number 3", then sums them. If the user inputs any data other than an integer for any of the entries, the code will print out "Invalid number entered" and only sum the valid integers entered. What I would like to do is force the user to enter only valid integers and the code remain repeating "Enter number X" for that entry until the user does so. Could someone please let me know how this is done? Thanks. Ron
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int counter = 0;
int addSum = 0;
while (counter < 3) {
counter++;
int numberEntered = 0;
System.out.println("Enter number " + counter + " :");
boolean hasNextInt = myScanner.hasNextInt();
if (hasNextInt) {
numberEntered = myScanner.nextInt();
// myScanner.nextLine(); //why can't myScanner.nextLine()
// could go here right after the number entered
// is captured and stored in the numberEntered variable;
addSum = addSum + numberEntered;
} else {
System.out.println("Invalid number entered");
}
// myScanner.nextLine only works if placed here before
// closing of the while loop;
myScanner.nextLine();
}
System.out.println("The sum of the numbers entered are " + addSum);
myScanner.close();
}
}
Right now, you are always incrementing the counter no matter what:
while (counter < 3) {
counter++;
Even when the user enters an invalid number, you increment the counter, causing the loop to run 3 times as usual, hence the current behaviour.
You should only increment the counter when the user enters a valid number:
if (hasNextInt) {
counter++;
numberEntered = myScanner.nextInt();
Now you will see that the prompts say "Enter number 0 :", which is probably not desirable. You can fix this by printing (counter + 1) when you are printing the prompt:
System.out.println("Enter number " + (counter + 1) + " :");

Bingo game Java

I'm trying to write a java code with(bingo game),(bullseye game)
the rules are simple:
computer picks 4 numbers
user input 4 numbers
must check the user input is between 1 to 10
If the user input exists in the computer randomized numbers it will be 1 bulls
If a number exist in the same location of the computer randomized number it will show 1 "eye"
Max limit is 20 tries until the user is considered "failed"; I need to print each round how many bulls were and how many eye were by the user input;
Example:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
my code prints 0 and 0 at the end.
Thanks for the help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
ArrayList<Integer> randNumbers = new ArrayList<>();
Random random = new Random();
String input;
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please press enter to begin");
input = sc.nextLine();
}while (!input.equals(""));//loop while user doesn't press ENTER
for (int i = 0; i < 4; i++){
randNumbers.add(random.nextInt(10) + 1);//loop to fill the randNumbers arraylist with random numbers
}
/*
randNumbers.add(3);
randNumbers.add(2);
randNumbers.add(9);
randNumbers.add(9);
*/
System.out.println("My random numbers: " + randNumbers.toString());
int counter = 0;
int bulls = 0;
int eyes = 0;
do {
System.out.println("Please enter 4 numbers between 1-10");
number = sc.nextInt();
if (number > 0 && number <= 10){
//System.out.println("index of rand: " + randNumbers.indexOf(number));
//System.out.println("count: " + counter);
if (randNumbers.indexOf(number) == counter){
eyes++;
System.out.println("eyes++");
}else if (randNumbers.contains(number)){
bulls++;
System.out.println("bulls++");
}
counter++;
System.out.println("Number " + counter + " introduced. " + (4 - counter) + " more to go.");
}else {
System.out.println("Wrong number.");
}
}while (counter < 4);//loop for user to introduce valid numbers
System.out.println("You scored " + bulls + " bulls and " + eyes + " eyes.");
}
}
Try this piece of code. Note that I used ArrayList rather than an array, as it offers methods such as .contains() and .indexof().
WARNING: Code will fail if the randNumbers arraylist contains two numbers that are equals, such as the 3-2-9-9 array that is commented when you input 9-9-9-9 as your number guesses. This is because .indexof() method:
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
Meaning the code fails to account the last 9 as it will compare the count index (3) to the first occurrence of 9 in the randNumbers, which is 2, making it false and not increasing eyes count.
Since I'm short on time, and this is an assigment you have and just copying it won't teach you much, I'll leave it to you to solve this specific case (I already told you what's wrong, won't be difficult to solve).

Java: Display the complete set of unique values input after the user enters each new value

I need to write a code that "Display the complete set of unique values input after the user enters each new value." Such as:
The·complete·set·of·unique·values·entered·is:↵
Unique·Value·1:·is·100↵
Unique·Value·2:·is·10↵
Unique·Value·3:·is·20↵
I have attached my code below, and have the code completed, however, it seems to come across errors on my very last line to produce the last "this is the first time (user input) has been entered" & the unique value portion results of Unique Value # is (user input that's unique and stored in array). There seems to be an error in the very last System.out.println("Unique...) line.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class DisplayUniqueValueInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// creating an ArrayList from user input
ArrayList<Integer> userInputs = new ArrayList<Integer>(5);
// prompt user and store input
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
count++;
if (count == 5)
break;
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
} // end while statement
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < 5; i++) {
System.out.println("Unique Value" + userInputs[i] + "is:" + " ");
}
} // end main method
} // end of class
A little off-topic but if you must store unique elements, you normally go for a Set. That being said, in the portion of the code where you collect the user input, you are asking for 5 numbers but storing 4 e.g.:
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
// count++;
// if (count == 5) if you break here, the code below won't be reached
// break; thus you will never store the last user input
// Lists have a method contains that does exactly what you are trying to do
// Consider using ifExists = userInput.contains(a)
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
// consider breaking here after you have collected the last user input
// alternatively, use a do{ ... } while(); loop
count++;
if (count == 5)
break;
} // end while statement
You are not printing the iteration variable i e.g.:
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value " + (i + 1) + ": is " + userInputs.get(i));
}
Also as mentioned in another answer, in your for-loop the variable i must go up to < userInputs.size() since if you try to go up to 5, it will break if the user entered duplicate values.
For the last loop, you should do this instead, because your array is to store unique numbers, right? So if there is less than 5 unique number, your program will break, and why don't use Set instead?
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value" + userInputs.get(i) + "is:" + " ");
}
Your error is because in the last for loop you try to access your list with userInputs[i] instead of userInputs.get(i)
If you want to accept and print only unique value, Perhaps use Set instead of ArrayList. Example:-
public static void main(String args[]){
Set<Integer> numbers = new HashSet<>();
for(String input : args){
Integer num = Integer.parseInt(input);
if(!(numbers.add(num))){
throw new IllegalArgumentException("Number already have");
}
System.out.println("Unique number =" + num);
}
}
A Set is a collection that contains no duplicate elements. Refer to its javadoc for details.
** Sample above just for brevity, you may retrofit your program with Set type.

FOR Loop array in JAVA, not working

Can someone point out what is wrong with my program?
I have done most of it but I can't seem to find what's wrong with it.
It doesn't ask the user for the "enter your grade" prompt for each course.
This is for an array assignment for school. Here is my code.
I am having difficulties figuring out what is wrong with the for loop I made specifically the for loop.
This program is supposed to ask the user for their courses and then the user enters their grades for that course.
If possible, please provide me hints on what I am doing wrong.
import java.io.*;
public class StudentMarks {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
i++;
System.out.println("Please enter course name " + i);
course = br.readLine();
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
}//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
Instead of i++ use
System.out.println("Please enter course name " + (i+1));
you do not need any nested loop
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
instead use
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
HERE is the Full code if you still having trouble understanding it let me know .
import java.io.*;
public class sort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
System.out.println("Please enter course name " + (i+1));
course = br.readLine();
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
}
I think you didnt intend to have the i++ / j++ in your for loops (first statement).
The third “parameter” of the loop head actually tells the program what to do, when it reaches the end of the loop. Therefore you increment twice each time.
Your inner loop (with int j = i--) has a condition that is always false, and so it's body is never executed.
The line of code:
j = i--
isn't as simple as it seems and can be broken down into two lines:
j = i;
i = i - 1;
Note that j is set to the value of i, and only after that does i get decremented. So if j is set to i, and then i becomes i - 1, i will be one less than j. So the condition of the for loop i.e. j < i, will always be false, and so the body of the loop will never be executed.
Example:
i = 5;
j = i--;
this boils down to
i = 5;
j = i; //j is 5
i = i - 1; //i is 4
j < i; //5 < 4 is false, inner for loop not executed
Hope this helps!

java array that accepts input of put name mark, quit and get name (not working)

im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}

Categories