I want to create an MenuBased ArrayList in java - java

import java.io.*;
import java.util.*;
import java.lang.*;
class MenuList
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
List<String> items=new ArrayList<String>();
int y;
do
{
//String n="";
//int i=0;
System.out.println("********************");
System.out.println(" MENU");
System.out.println("********************");
System.out.println("Press 1 to Add an Array with to List : ");
System.out.println("Press 2 to Remove an Array from the List : ");
System.out.println("Press 3 to Add Array at an Index in the List : ");
System.out.println("Press 4 to Replace an Array in the List: ");
System.out.println("Press 5 to Show the Output : ");
System.out.println("Press 6 to exit");
y=sc.nextInt();
//int [] arr= new int[5];
switch(y)
{
case 1:
System.out.println("Enter the Element to be added " );
items.add(sc.next());
break;
case 2:
System.out.println("Enter the Element's postion which you want to Remove " );
items.remove(sc.nextInt());
break;
at case 3 and 4 i am getting the same error as before. input mismatch
case 3:
System.out.println("Enter the Elements postion and Element to be added : ");
items.add(sc.nextInt(),sc.next());
break;
index starts from 0 and increments. i input 4 values and then tried to
change the value at 2nd index it showed me the Input mismatch error
case 4:
System.out.println("Enter the Elements postion and Element to be replaced :");
items.set(sc.nextInt(),sc.next());
break;
case 5:
System.out.println("Values you stored are as follows : " +items );
break;
case 6 :
break;
default:
System.out.println("You Have Entered Invalid Choice ");
}
}
while(y != 6);
}
}

The first problem with adding is obvious, don't add 'n' in:
items.add(sc.next(n))
You didn't use it in next lines which is correct

I got your code working, and also a few comments:
Basically, you need to move
List<String> items=new ArrayList<String>();
outside the doloop. Instead of modifying it, you're recreating it in each iteration. And use sc.next() instead of sc.next(n) to read strings.
You need a bunch of error checking here, things blowup if any entry errors are made, and that's very easy to do (make an error).
Your display messages need improvement, instruct the user what needs to be entered in what order

Related

Adding user input for arrayList.set

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

for loop - looping more than its supposed to?

public static void choice( String arrayString[], double arrayReal[])
{
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("1.display mark");
System.out.println("2.exit");
choice = sc.nextInt();
while (choice !=2 && choice != 1)
{
System.out.println("invalid input enter again");
choice = sc.nextInt();
}
switch (choice)
{
case 1:
output(arrayString, arrayReal);
break;
case 2:
System.out.println("exiting");
break;
default:
System.out.println("invalid choice choose between 1 and 2");
choice = sc.nextInt();
}
}
public static void output(String arrayString[], double arrayReal[])
{
String name;
Scanner sc = new Scanner(System.in);
for (int i=0;i<arrayString.length;i++)
{
System.out.println(arrayString[i]);
}
System.out.println("enter stident name");
name = sc.nextLine();
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
for (int j=0;j<arrayString.length;j++)
{
if (arrayString[j].equals(name))
{
System.out.println("mark of " + arrayString[j] + "is " + arrayReal[j]);
}
}
im trying to validate the student name and if it doesnt equal to any of the names in the array return back to the menu. it does go back to the menu but the problem is after going back to the menu even if i type the correct student name if keps going back to the menu. i thought for loops were supposed to loop set amount of times and pass to the next code?? is that right? also is my approach correct? ive tried putting if else in the last for loop but that didnt end up as i wanted it to as well. any help is appreciated thanks!
EDIT-
thanks for spotting the mistake. fixed !arrayString.equals(name) to !arrayString[k].equals(name) but still the same problem
Your problem ist here:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
You are comparing an Array String[] arrayString with a String name. They are never going to be treated as equal and therefor your choice method is allways called.
Also the whole loop is totally pointless as you never use your loop index k for anything.
You don't need a loop here at all. Instead you can simply convert the String array to a temporary list and check if it contains your input:
if(!Arrays.asList(arrayString).contains(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
Edit:
here a short main Method that can be used for testing:
public static void main(final String[] args) {
final String[] test = { "Mark", "Peter" };
final double[] test2 = { 1, 2 };
choice(test, test2);
}
Input/Output:
OUTPUT: 1.display mark
OUTPUT:2.exit
INPUT: 1
OUTPUT: Mark
OUTPUT: Peter
OUTPUT: enter stident name
INPUT: Mark
OUTPUT: mark of Markis 1.0
The logic at this part, after adding the index, is still wrong:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString[k].equals(name))
{
System.out.println("invalid name");
...
}
}
this will print "invalid name" for every name in the list that is not the given name. Example: if the first name in the array does not match, you will get a message (and choice called), no matter if the second entry matches.
One way is to search the whole array until you find the name and then act on the result:
boolean found = false;
for (int k=0;k<arrayString.length;k++)
{
if(arrayString[k].equals(name))
{
found = true;
break; // stop searching
}
}
if (!found)
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}

Create a new object from user input using array and not ArrayList in Java

I've a problem creating a new object dynamically using the user input. I know how to do it using ArrayList but I was wondering if it would be possible to use only one array? Object 1 and Object 2 extend from MainObject.
I currently have:
import java.util.Scanner;
public class Main
{
public static void main (String args[])
{
MainObject[] Main = new MainObject[99];
//^objects created will be added to this array^
int input;
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("1. Add a new object 1");
System.out.println("2. Add a new object 2");
System.out.println("3. Display all object info");
System.out.println("4. Quit");
System.out.print("Please enter either 1 to 4: ");
input =(scanner.nextLine());
switch(input) {
case 1 :
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
case 2 :
object2 obj2 = new object2();
System.out.println("Please enter name of object: ");
obj2.setName(scanner.nextLine());
obj2.display();
case 3 :
//this is where the for loop should be to display all the info of obj 1 and 2
case 4 :
System.out.println("Thank You");
break;
}
}
while (input==1 || input==2 || input==3)
So I have added the objects into the array like so
case 1 :
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
Main[0] = obj1;
break;
case 2 :
object2 obj2 = new object2();
System.out.println("Please enter name of object: ");
obj2.setName(scanner.nextLine());
obj2.display();
Main[1] = obj2;
break;
case 3 :
int x = 0;
for (x=0; x<Main.length; x++)
{
Main[x].displayComputer();
}
break;
Compiled and run and it works fine but it gives me a java.lang.NULLPointerException:null and the highlighted code that causes the problem is
Main[x].displayComputer();
ArrayLists can have variable size, while an array is of static size. That is, once you allocate an array, you cannot append/insert new elements. However, you can allocate a large array, then fill it in piece-by-piece. In general, the process looks like this:
int nextSpot = 0; //next spot to fill in array
while (still_getting_input) {
if (supposed_to_insert) {
if (nextSpot_in_valid_range)
myArray[nextSpot++] = value_to_insert;
else
System.out.println("Invalid operation!"); //cannot insert.
}
}
So, your program would look like:
import java.util.Scanner;
public class Main
{
public static void main (String args[])
{
MainObject[] Main = new MainObject[99];
//^objects created will be added to this array^
String input;
Scanner scanner = new Scanner(System.in);
int nextSpot = 0;
do
{
System.out.println("1. Add a new object 1");
System.out.println("2. Add a new object 2");
System.out.println("3. Display all object info");
System.out.println("4. Quit");
System.out.print("Please enter either 1 to 4: ");
input =(scanner.nextLine());
switch(input) {
case 1 :
if (nextSpot < Main.length) {
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
Main[nextSpot++] = obj1;
}
else {
System.out.println("Error!");
}
break;
// etc.
}
}
while (input==1 || input==2 || input==3)
There are some other problems with your code (particularly, your usage of a switch statement; you're going to experience fall-through), but this answers the question you asked.
I would do something like this,
int index = 0;
do {
...
case 1 :
...
Main[index++] = obj1;
break;
case 2 :
...
Main[index++] = obj2;
break;
case 3:
// Iterate over the loop till index
} while ((index < Main.length && (input==1 || input==2)) || input==3)
Your question is actually array and arraylist when being iterated, how long do they go ?
When you iterate over array, its normal iteration goes to size you have declared for the array at the initialization time. But for arrayList, it is that how many elements are actually present in arrayList. Internally arrayList doubles its size when ever it wants after a default capacity.
You can rather keep a track of number of elements you are adding to it.
Or just do a NULL POINTER CHECK on the indexed element
Please note that you missed out loading the values into the Main[] array since only the object obj1 (and similarly obj2 ...) is initialized. Maintain an index and add the objects accordingly to the array:
int index=0;
...
case 1 :
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
Main[index++] = obj1;
...
while((index < 100 && (input==1 || input==2 || input==3))

How do I keep track the number of times a specific input was entered by the user?

My program should ask the user to enter some grades. After the input is finished, the program has to show which grade was entered how many times (or in another word, how many times each grade was entered).
For example, if the user enters grade 3 two times, thats menas total 2 students has got the grade 3. If the grade F is entered 3 times, that means 3 students has got the failing grade F, and so on....
The final output should look something like this:
Example output:
grade F= 3 students
grade 3= 2 studnets
and so on....
...........................
...........................
Now my problem is with keeping track of each grade and print them out telling how many times (also means how many students got each specific grade) each of the grade was entered. I can't come up with idea to solve it.
My code:
package studentgrade;
import java.util.*;
public class StudentGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many total grade you want to enter (Depending on the total number of students)? ");
int totalStudents = input.nextInt();
String grade[] = new String[totalStudents];
//asking user to enter grade
for (int i = 0; i < totalStudents; i++) {
System.out.println("Enter grade " + (i + 1) + ": ");
System.out.println("Choose only between grade 3 and F:\n");
grade[i] = input.next();
if (grade[i] == "3") {//3 defines the only passing grade
//Store that into a variable
} else if (grade[i].equalsIgnoreCase("F")) {//F defines the failing grade
//Store that into a variable
}//else{
//System.out.println("Invalid input. Try again");
//}
}
//Now print out which grade was entered how many times
}
}
Define, at the top, a variable resembling each grade and set them to 0, and then, each time in the "if" statement, add one to the corresponding variable. variable++.
At the end, use
System.out.println("Grade 3: " + variable3);
System.out.println("Grade F: " + variableF);
Also, use .equals method to compare two strings in the if statement
If you don't need the sort of introduced values, simply create an array with your needed size n (don't see exactly what means from 3 to F).
int[] grade = new int[n];
If all inputs where numbers you can make direct:
grade[input.next()] ++;
Then, as all inputs are not int you can solve it with a switch
switch(input.next()) {
case "3":
grade[0] ++;
case "2":
grade[1] ++;
....
case "F":
grade[n-1] ++;
}
This is a good use for a Map. Right now your only storing the inputs 3 and F but if you wanted to adapt this program to have more grades this would scale perfectly and it is a clean and neat solution.
// the map to store how many times a grade was entered
private static final Map<String, Integer> gradeSumMap = new HashMap<String, Integer>();
public static void addToGradeSum(String key, int num) {
if(gradeSumMap.get(key) == null) {
gradeSumMap.put(key, num);
} else {
gradeSumMap.put(key, gradeSumMap.get(key) + num);
}
}
public static void printGradeSumMap() {
for(String key : gradeSumMap.keySet()) {
System.out.println("grade " + key + " = " + gradeSumMap.get(key));
}
}
// this needs to also be .equals or .equalsIgnoreCase
if (grade[i].equals("3")) {
addToGradeSum(grade[i], 1);
} else if (grade[i].equalsIgnoreCase("F")) {
addToGradeSum(grade[i], 1);
}
then just call printGradeSumMap() when you want to print it

Trouble trying to restart my Java program

After looking up numerous ways to restart a Java program within itself, a while loop seemed like the easiest option. Here's an example of a basic calculator program I'm trying this with:
import java.util.Scanner;
class a {
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done)
{
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
add addObject = new add();
addObject.getSum();
break;
case 2:
sub subObject = new sub();
subObject.getDifference();
break;
case 3:
times multObject = new times();
multObject.getProduct();
break;
case 4:
divide divObject = new divide();
divObject.getQuotient();
break;
case 5:
remain remObject = new remain();
remObject.getRemainder();
break;
case 6:
avg avgObject = new avg();
avgObject.getAvg();
break;
case 7:
interest intObject = new interest();
intObject.getInterest();
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
}
However, this seems to throw out a NoSuchElementException at the end of the first time through the loop, and crashes the program. The function of this class is to take the initial input from the user to determine which class to use, which will determine which mathematical operation to perform. Everything works fine without the while (!done) loop.
Example usage:
McMackins Calc v2.0 (Now with fewer crashes!)
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
1
How many addends?
1
Enter your numbers now.
1
You have entered 1 addend.
The sum is: 1.0
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
Enter a valid integer.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at a.main(a.java:13)
I've also tried just having the other classes refer back to this one, but since main is a static method, I cannot access it the way I intended.
Note that I'm a bit of a beginner at Java, which is why my program is pretty simple, so try to keep it simple if it can be, or post code and then in DETAIL explain what it means so I can not only fix this problem, but future ones as well.
Thank you!
EDIT:
The code is formatted better within my editor. The braces came out in odd positions when I posted it here.
Since apparently a is written correctly, this is my add class. Hopefully this will clear something up.
import java.util.Scanner;
public class add {
public void getSum(){
Scanner input = new Scanner(System.in);
double total, addend;
int entries, count;
total = 0;
count = 0;
System.out.println("How many addends?");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
entries = input.nextInt();
System.out.println("Enter your numbers now.");
while (count < entries){
while (!input.hasNextDouble()){
System.out.println("Enter a valid number.");
input.next();
}
addend = input.nextDouble();
total = total + addend;
count++;
if (count == 1){
System.out.println("You have entered " + count + " addend.");
}else if (count > entries){
System.out.println("You have entered too many addends! Contact program developer.");
}else{
System.out.println("You have entered " + count + " addends.");
}
}
System.out.println("The sum is: " + total);
input.close();
}
}
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done) {
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
case 4:
System.out.println("4");
break;
case 5:
System.out.println("5");
break;
case 6:
System.out.println("6");
break;
case 7:
System.out.println("7");
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
This seemed to work for me so perhaps the error is something to do with your own classes (add, divide) etc.
Also, it's best to keep with convention when creating your own classes by capitalizing the first letter e.g. "add" should be "Add".
You could probably make this a little bit easier to read by building a general "Operations" class which holds an add method, a subtract method etc.
EDIT:
try this for your add method:
public static int add() {
Scanner s = new Scanner(System.in);
int counter = 0;
System.out.println("How many numbers to add?");
int numCount = s.nextInt();
for(int i = 0; i < numCount; i++) {
System.out.println("enter number");
counter += s.nextInt();
}
return counter;
}
Use bufferedreader and inputstream instead of Scanner class. This class creates a lot of bugs and errors, since sometimes it takes more arguments, that you expect it to take.
Also:
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
Your using hasNextInt method wrong, instead of it try to make simple while loop with Boolean and input.next() should be replaced with input.nextLine().
Another thing, you should check,if user typed integer instead of string or something in the while loop and it range. If everything is okay, you should change Boolean value to true and make him go out of the while loop.
For future users who are wondering how to fix this issue, through some reprogramming, I discovered that my problem was closing the input variable BEFORE the end of the loop. By having the program restart indefinitely and only close input when done, this program works fine.
Thanks to Benjamin's response, I am currently in the process of cleaning up and shortening my code by way of for loops.

Categories