Adding user input for arrayList.set - java

I've been working on the following assignment:
This program should create an ArrayList called Book List. The program
should display a menu to allow the user to choose from the following options:
Enter 1 to add a book to the list:
Enter 2 to edit a book to the list:
Enter 3 to remove a book from the list:
Enter 4 to display the list of books:
Enter 5 to quit:
The program should use a case/switch statement and switch on the users choice. The program should continue until the user enters 5 to quit.
Case 1 should use BookList.add to add books to the ArrayList.
Case 2 should use BookList.set to edit books to the ArrayList.
Case 3 should use BookList.remove to remove a name from the list (Ask the user to enter the index number of the book to delete from ArrayList).
Case 4 should use a for loop to display all books in the ArrayList
along with their index number.
(Sample output) Your output should look similar to:
**********The Book List*********
Index: 0 Name: Stranger in a Strange Land
Index: 1 Name: PHP and MySQL
Index: 2 Name: HTML & CSS
Index: 3 Name: Love Story
Index: 4 Name: The Day the Earth Stood Still
I am having trouble with ArrayList.set. I can not figure out how to take user input (the index number and the corrected book title) to update the array list. That's not the end of my issues with this program, but any help on ArrayList.set would be greatly appreciated.
import java.util.ArrayList;
import java.util.Scanner;
public class BookList {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//Create array
ArrayList<String> bookList = new ArrayList<String>();
//Add a few books to the array bookList
bookList.add("A Game of Thrones");
bookList.add("A Clash of Kings");
bookList.add("A Storm of Swords");
bookList.add("A Feast for Crows");
bookList.add("A Dance with Dragons");
//Display the items in bookList array and their indices.
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
System.out.print("\n");
//declaring variables
int menuID = 0;
int changeIndex = 0;
int delIndex = 0;
String addTitle = "";
String corrTitle = "";
//Menu
System.out.println("Enter 1 to add a book to the list");
System.out.println("Enter 2 to edit a book in the list");
System.out.println("Enter 3 to remove a book from the list");
System.out.println("Enter 4 display the list of books");
System.out.println("Enter 5 to quit");
System.out.println("Enter a menu number (1-4 or 5 to Exit): ");
menuID = input.nextInt();
while (menuID != 0)
{
if (menuID >=1 && menuID <= 4)
{
switch (menuID)
{
case 1:
System.out.println("Enter the book to add: ");
addTitle = keyboard.nextLine();
bookList.add(addTitle);
System.out.print("\n");
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 2:
System.out.println("Enter index number of the book to change: ");
changeIndex = keyboard.nextInt();
System.out.println("Enter the corrected book name: ");
corrTitle = keyboard.nextLine();
bookList.set(changeIndex, corrTitle);
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 3:
System.out.println("Enter index number of the book to remove: ");
delIndex = keyboard.nextInt();
bookList.remove(delIndex);
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 4:
System.out.println("******** The Book List ********");
for (int index = 0; index < bookList.size(); index++)
{System.out.println("Index: " + index + " Name: " + bookList.get(index));}
break;
case 5:
System.out.println("Goodbye!");
break;
}}
else if (menuID >=1 && menuID <= 4)
System.out.println("You must enter a number 1-5:");
System.out.println("Enter a menu number (1-4 or 5 to Exit): ");
menuID = input.nextInt();
}
}
}

You should be using only one Scanner object with the same source, unless you had a really complicated way to traverse the input, which probably isn't the case here. So your code should look something like this:
// Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
// ...
menuID = input.nextInt();
while (menuID != 0)
{
if (menuID >=1 && menuID <= 4)
{
switch (menuID)
{
case 1:
// ...
addTitle = input.nextLine();
// ...
Now, there's another issue because you're calling Scanner.nextInt, which gets you the next integer, but won't consume the rest of the line after taking the integer, so when you call Scanner.nextLine it will get you the rest of that previous line instead of the new line you're expecting. To fix that, you could call a dummy Scanner.nextLine after each Scanner.nextInt, like this:
menuID = input.nextInt();
input.nextLine(); // Consumes the rest of the line
Or you could get the whole line every time and parse the integer it contains, using Integer.parseInt, like this:
menuID = Integer.parseInt(input.nextLine());
Here's the working code using the second option (which I find better for this case)
As a side note, you're asking the user to exit with 5, but your while depends continues as long as the menuID is not 0

Related

How to solve Cannot invoke "String.compareTo(String)" because "<parameter1>[<local3>]" is null?

import java.util.Scanner;
public class Search {
static Scanner scanner = new Scanner(System.in);
static Scanner kb = new Scanner(System.in);
static Scanner kb2 = new Scanner(System.in);
public static void main (String[] args)
{
int choice;
System.out.print("Choose a number of students: ");
int n = scanner.nextInt();
String name[] = new String[n+1];
String course[] = new String[n+1];
int ID[] = new int[n+1];
for(int i=1;i <= n; i++)
{
System.out.print("Enter ID number " + i + ": ");
ID[i] = scanner.nextInt();
System.out.print("Enter Student name " + i + ": ");
name[i] = kb.nextLine();
System.out.print("Enter Student course " + i + ": ");
course[i] = kb2.nextLine();
System.out.println("----------------------------------------");
}
do
{
choice = menu();
if(choice == 1)
{
sortID(ID);
printValues(ID);
}else if(choice == 2)
{
nameSort(name,n);
printName(name,n);
}else if(choice == 3)
{
}
}while(choice !=0);
}
public static int menu()
{
System.out.print("\n1. Sort by ID\n2. Sort by Name\n3. Search by ID\n4. Search by Name\n5. Search by Course\n6. Display Records In table Form.\nYour Choice: ");
return scanner.nextInt();
}
public static void sortID(int []id)
{
int temp;
int index, counter;
for (counter=0; counter < id.length -1; counter++) {
for (index=0; index < id.length - 1 - counter; index++) {
if (id[index] > id[index+1]) {
temp = id[index];
id[index]=id[index+1];
id[index+1]=temp;
}
}
}
}
public static void printValues (int[]array) {
System.out.println ("\nSorted Id Number: ");
for(int i = 1; i < array.length; i++){
System.out.print ("\n" + array[i]);
}
}
public static void printName (String[]array,int a) {
for (int i = 0; i <= a - 1; i++)
{
System.out.print(array[i] + ", ");
}
}
public static void nameSort(String[] name,int a)
{
String temp;
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++) {
if (name[i].compareTo(name[j])>0)
{
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
}
}
The sorting works on the id but i have problems in my names it wont push through the bubble sort and say its null, im just starting learning this language and it would be a great help. Ive been working on this since last night and ive tried transffering it under the if else(choice == 2) still it says null.
Choose a number of students: 2
Enter ID number 1: 123
Enter Student name 1: Mark JAw
Enter Student course 1: JSJS
----------------------------------------
Enter ID number 2: 221
Enter Student name 2: Ak akw
Enter Student course 2: jdj
----------------------------------------
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 1
Sorted Id Number:
123
221
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 2
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.compareTo(String)" because "name[i]" is null
at Search.nameSort(Search.java:95)
at Search.main(Search.java:41)
PS C:\Users\Bingus\Documents\Projects>
String name[] = new String[n+1];
Suppose for example that you read in a value of 3 for n. This code means that you will allocate 3+1 = 4 elements in name (and likewise in the other arrays). You do not want to allocate 4 elements. You will read 3 names, so you want to allocate 3 elements.
The valid indices for your array will be 0, 1, 2 and 3. You do not want 3 to be a valid index for your array. You want only 0, 1 and 2 to be valid indices, which if you count, you will notice makes 3 different indices.
for(int i=1;i <= n; i++)
In this loop, you will use values of 1, 2 and 3 for i, and thus assign to indices 1, 2 and 3 of name (as well as the other arrays). You do not want to do this. The result is that name[0] will remain null. You want to start the loop at 0 so that you use every element of the arrays. You want to use i < n as your loop condition, because once you correctly only have n elements in the array, n is no longer a valid index.
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++) {
if (name[i].compareTo(name[j])>0)
When the exception happens, it happens because you correctly start scanning the array from the beginning, but have incorrectly filled (and sized) the array. You pull a null value out of the array (that shouldn't be there) and try to .compareTo another value (which doesn't work, because you can't call a method on a null). A similar problem would occur (if you got that far) in your other sorting method.
(Unless it is for an assignment, you should not implement sorting yourself. You should use java.util.Arrays.sort.)

java.lang.ArrayIndexOutOfBoundsException?

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.

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
}
}
}
}

Displaying array values through object that references other methods not displaying with for loop

Basically, the point of my program is a payroll program for the user to input amount of employees, then with that same amount of employees go through the process of indicating what kind of employee it is, and then proceed to enter information of employee based on type. Right now, I am going one at a time and first starting out with hourly. I managed to get the output I wanted until I end up completing the while loop's condition to go on and output the resulting table but it does not output the results and only outputs the column labels. I decided to use a for loop so that it continues to display until it reaches a number greater than the size. I checked to see if I was using correct formatting for the array[e].method(); but cant seem to catch anything wrong so far.
Could it be a possibility of the parameters not matching or probably a misuse of it?
Thanks in advance.
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the Company's Payroll System!");
System.out.println("Please enter the amount of employees in the company.");
int size = in.nextInt();
Employee [] staff = new Employee [size];
int i = 0;
while (i != staff.length )
{
System.out.println("Enter employee type (Choose Hourly, Salary, or Manager)");
System.out.println("Press 4 to exit.");
String emptype = in.next();
if (emptype.equalsIgnoreCase("Hourly"))
{
System.out.println("First name:");
String first = in.next();
System.out.println("Last name:");
String last = in.next();
System.out.println("Employee ID (7 digits):");
Float identification = in.nextFloat();
System.out.println("Job Title:");
String title = in.next();
System.out.println("Amount employee makes per hour: ");
double hour = in.nextDouble();
staff [i] = new HourlyEmployee(first, last, identification, title, hour);
i++;
}
}
System.out.println("FIRST NAME \t LAST NAME \t ID \t JOB TITLE \t Weekly Salary");
for (int e = 0; e > size; e++)
{
System.out.printf("%5d", staff[e].getfirstName() + staff[e].getlastName() + staff[e].getId() + staff[e].getTitle() + staff[e].weeklyPay() );}
}
}
In the for loop your condition is wrong. It should be:
for (int e=0; e < size; e++)

output value of user inputs inside an array java

I'm making a program where a user enters how many inputs the user wants. Example if the user enter's 3, then 3 user inputs will appear. The output of this program goes something like this:
----------------------------------
Enter How Many Inputs: 3
enter name:
rendell //value to be outputted
enter age:
20 //value to be outputted
enter gender:
male //value to be outputted
-----------------------------------
Now, I want to store those entered values somewhere to be outputted separately after but I have no idea how to do it. I tried to use the ctr1 variable but it only outputs the value of the last user input.
Here is my code:
Object stud1 [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}};
String ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int i = 0; i<num1;i++){
System.out.println(pers[1][i]);
ctr1 = in.readLine();
}
The problem is that you are only assigning all the input in one reference to the String thus you can print all the input the user just gave.
solution:
You can use an array of String to put all the values from the inputted data if the user
sample:
String [] choices = { "enter name:","enter age:","enter gender:"};
String ctr1[];
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(scan.nextLine());
ctr1 = new String[num1];
for (int i = 0; i < num1; i++) {
System.out.println(choices[i]);
ctr1[i] = scan.nextLine();
}
for(int i = 0; i < ctr1.length; i++)
{
if(i == 0)
System.out.println("Name: "+ ctr1[i]);
else if( i == 1)
System.out.println("Age: "+ ctr1[i]);
else if( i == 2)
System.out.println("Gender: "+ ctr1[i]);
}
result:
Enter How Many Inputs: 3
enter name:
Rod_algonquin
enter age:
12
enter gender:
male
Name: Rod_algonquin
Age: 12
Gender: male

Categories