How to add elements using ArrayList in java? - java

I'm now learning all about ArrayList. I've created a small code for practice purposes using ArrayList but there has been an unwanted output.
My output should be like this:
********************\
1 - Add names
2 - Show names
Enter mode:1
Enter name:Bruno
Do you want to add a name again?(y/n):y
Enter name:Django
Do you want to add a name again?(y/n):n
********************\
1 - Add names
2 - Show names
Enter mode:2
Bruno
Django
but instead, my output is like this:
********************\
1 - Add names
2 - Show names
Enter mode:1
Enter name:Bruno
Do you want to add a name again?(y/n):y
Enter name:Django
Do you want to add a name again?(y/n):n
********************\
1 - Add names
2 - Show names
Enter mode:2
When I have already added the names and then press n, I will choose next, the number 2 for displaying names. But it didn't show anything. I can't figure out the algorithm. It looks like the ArrayList is resetting its elements whenever it went back to choosing mode.
Here is my code:
package Practice;
import java.util.Scanner;
import java.util.ArrayList;
public class Practice1Main {
public static void main(String[]args){
ArrayList<String>namelist=new ArrayList<>();
Scanner hold = new Scanner(System.in);
String response, name;
int mode = getMode();
switch(mode){
case 1:
do{
System.out.print("Enter name:");
name = hold.nextLine();
namelist.add(name);
System.out.print("Do you want to add a name again?(y/n):");
response = hold.nextLine();
if(response.equalsIgnoreCase("n")){
getMode();
}
}while(response.equalsIgnoreCase("y"));
break;
case 2:
for(int x = 0;x < namelist.size();x++){
System.out.println(namelist.get(x));
}
break;
default:
System.out.print("ERROR!");
break;
}
}
public static int getMode(){
Scanner hold = new Scanner(System.in);
int mode;
System.out.print("********************\n");
System.out.print("1 - Add names\n");
System.out.print("2 - Show names\n");
System.out.print("Enter mode:");
mode = hold.nextInt();
return mode;
}
}

Well, a quick solution is below...
You miss setting mode when reading the getMode again, and also you do nothing when looping next time (the switch must activate again, you know.. I set it in a while loop). study below
while( mode == 1 || mode == 2 ) {
switch(mode){
case 1:
do{
System.out.print("Enter name:");
name = hold.nextLine();
namelist.add(name);
System.out.print("Do you want to add a name again?(y/n):");
response = hold.nextLine();
if(response.equalsIgnoreCase("n")){
mode = getMode(); // <---- set mode
}
}while(response.equalsIgnoreCase("y"));
break;
case 2:
for(int x = 0;x < namelist.size();x++){
System.out.println(namelist.get(x));
}
mode=-1; // <--- break out
break;
default:
System.out.print("ERROR!");
mode = -1;
break;
}
}
}

Related

No Such Element Exception while scanning multiple inputs

I am new to java programming , and i am trying to learn the usage of classes and objects in java programming , while writing the following code i got an exception
java.util.NoSuchElementException
for sample input
5
1 2 3 4 5
here first line contains number of elements (in this case its 5),and next line contains elements.
while taking input inside the for loop in the class Election ,i am getting exception.
I tried searching on stack Overflow, and other resources too,but still can't figure out how to remove this exception.
import java.io.*;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
input.nextLine();
Election obj = new Election(n);
obj.getVotes();
}
}
class Election {
int n,v1,v2,v3,v4,v5,d;
public Election(int n) {
this.n = n;
v1=v2=v3=v4=v5=d=0;
}
public void getVotes() {
Scanner sc = new Scanner(System.in);
for(int i = 0 ; i < 1 ; i++) {
int var = sc.nextInt();
switch(var) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
}
Looks like I'm a bit late, but since your accepted answer is more of comment rather than a solution, I'll post this anyway.
Here is a simple deviation of the code you provided, but reaches the desired result!
I'll walk you through this:
public class MyTest {
public static void main(String[] args) {
//First of all, we need an instance of an Election-type object, so
//that we can call its methods and get votes from users.
Election e = new Election();
//Now we can easily call the method getVotes(), as defined in Election class.
//What happens here, is that the program will 'jump' to the getVotes() method
//and it will execute every line of code in that method. Then it will
//'return' to where it 'left off' in the main() method. Since getVotes()
//is of type 'void', it will not return anything. It will just 'jump' back.
e.getVotes();
//Now, you can use testResult() method, to see the values of the variables.
e.testResult();
}
}
Now, let's take a look at the class Election and how it works.
public class Election {
private final int VOTES_NUM = 1;
private int v1,v2,v3,v4,v5,d;
public Election() {
v1=v2=v3=v4=v5=d=0;
//print now, just to show that all variables = 0
testResult();
}
//Simple method that prints value of each variable. We use this for testing
public void testResult(){
System.out.println("v1 = "+v1);
System.out.println("v2 = "+v2);
System.out.println("v3 = "+v3);
System.out.println("v4 = "+v4);
System.out.println("v5 = "+v5);
System.out.println("d = "+d);
}
private int getInput(){
//First of all, we need a Scanner to take user input.
//You do that in your own code too. We simply move it in this method instead.
Scanner input = new Scanner(System.in);
//You also need variable to hold the user input.
//(Always give meaningful names to all entities)
int userInput;
System.out.print("Please enter vote number here: ");
//the next part has to be in a try-catch block,
//to avoid exceptions like InputMismatchException, etc..
try{
//Get user input
userInput = input.nextInt();
}
//If user enters letter, or symbol, or something else that isn't an integer,
//then inform them of the mistake they made and recursively call this method,
//until they get it right!
catch (InputMismatchException ime){
System.out.println("Please enter only a single number");
return getInput();
}
//If all goes well, return the user input
return userInput;
}
public void getVotes() {
//'VOTES_NUM' is a constant that defines the times the
//loop will iterate (like Macros in 'C')
for(int x=0; x<VOTES_NUM; x++)
int n = getInput();
//then let the switch statement increment one of the variables
switch(userInput) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
I think the code that you posted is missing. The code you posted is working properly and I achieved to get exception only when I wrote input.close() before the obj.getVotes(). When you want to close scanners you should do this after code finishes. Thus, if you close input after the obj.getVotes() you shouldn't get any error.
I tried running your code in a short main class, and I am not getting any exception. This is how I ran your method:
public static void main(String...args){
Election election = new Election(10);
election.getVotes();
System.out.println(election.v1);
System.out.println(election.v2);
System.out.println(election.v3);
System.out.println(election.v4);
System.out.println(election.v5);
System.out.println(election.d);
}
My input was 1 2 3 4 5 6 7 1 2 2 and the console output was:
2 // v1
3 // v2
1 // v3
1 // v4
1 // v5
2 // d
I did make a small change to your program. In the for loop inside the getVotes() method, I changed the condition to i<n (instead of i<1 in your posted code)

Having a error inputting strings in java

I'm currently working on a java project. I'm making a phone-book. I use switch to select whether the user wants to input the number or a name. The problem is that when I use the switch, which tells the user to input the number it works just fine, but when I use the 'choice' which makes the user input the String it doesn't work. In the run box I can't input the String. Pls help. Here's the code.
case 1 and case 3 aren't working.
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("\nWho would you like to call?");
name = scan.nextLine();
CallContact(name);
break;
case 2:
System.out.println("\nWhich coontact You Want to Search?");
break;
case 3:
System.out.println("\nWhich Name You Want to Save?");
name = scan.nextLine();
System.out.println("\nWhat is the Number of the person you want to save?");
long number = scan.nextLong();
SaveContact(name, number);
break;
default:
}
}
First of all you forgot put break in the default case but it does not effect to solve your usecase. This behavior is happen because when you are taking input with scan.nextInt() its set pointer at the end of that particular line. So just make habit if you are taking input of int then immediate you want to take input of string then just add extra scan.nextLine() before next input.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = new String();
int choice = scan.nextInt();
switch (choice) {
case 1:
scan.nextLine();// changes
System.out.println("\nWho would you like to call?");
name = scan.nextLine();
CallContact(name);
break;
case 2:
scan.nextLine();
System.out.println("\nWhich Contact You Want to Search?");
name = scan.nextLine();// changes
break;
case 3:
scan.nextLine();// changes
System.out.println("\nWhich Name You Want to Save?");
name = scan.nextLine();
System.out.println("\nWhat is the Number of the person you want to save?");
long number = scan.nextLong();
SaveContact(name, number);
break;
default:
break;//improve
}
}
Always use scan.nextLine() to receive the input and then convert received input in your desired format.
int choice = Integer.parseInt(scan.nextLine());

Calling previous switch in Java

I'm making a simple command line system where the user is supposed to be able to choose what they want to do. Therefore I've made a switch that takes a number as input and outputs whatever I choose, although I have now clue on how to return the user to the place where they can input again.
Let's say two of the cases looks like this:
case 6:
System.out.println("----- List of available Systems: ----- ");
break;
default:
System.out.println("You pressed a non-existing number. Please try again.");
break;
}
Now if the user (me) types any number above 6 it goes to the default and stops there. Is there anyway to make it jump back to the first "Menu" that asks for input?
Thank you in advance.
You can wrap it in a loop, e.g. a while:
while (var < 1 || var > 6) {
switch(var) {
...
}
}
However, this way, you need to make sure, that you won't be stuck in an infinite loop. This can be solved, e.g. by using a label:
end: while (var < 1 || var > 6) {
switch (var) {
case 1:
// do something
break end;
...
default:
System.out.println("Please try again.");
break;
}
}
This way, the break statements will break out of the while loop. Java labels are basically a very limited version of goto.
How about something more verbal..
int myno;
Scanner scanner =new Scanner(System.in);
boolean exit = false;
while(!exit){
System.out.println("1. Menu 1");//Modify your menu
System.out.println("2. Menu 2");
System.out.println("3. Menu 3");
System.out.println("4. Menu 4");
System.out.println("5. Menu 5");
System.out.println("6. Menu 6");
myno = scanner.nextInt();
switch(myno){
case 1 :
//do something
break;
case 2 :
//do something
break;
case 3 :
//do something
break; //add for remaining cases
case 7 :
exit = true;//for exit
break;
default :
// do something //set exit = true if you what to end the program for other inputs
}
}
try this

Trouble returning to command options using loops/ only one command is being run (JAVA)

This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.

Printing different sentences depending on user input

I am wondering how to print a particular sentence depending on user input.
In the scenario below, if the user enters "B" I would like to print the words "You have selected B" however if the user selects C I would like to print the word "You have selected C".
import java.util.Scanner;
public class Trial extends Register
{
//I want to load the register which will be option B
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter A to make a purchase & receive your change");
System.out.println("Enter B to load the Register");
System.out.println("Enter C to write the contents of the Register to a
web Page");
System.out.println("Enter D to exit the program");
}
How about:
String input = // read input from scanner;
if(input.length() == 1) {
switch(input.charAt(0)) {
case 'A':
// make purchase
break;
case 'B':
// load register
break;
// Similarly case C and D
default:
// possibly invalid input as well
}
} else {
System.out.println("Invalid input");
}
If you are using Java 7+, you can use a switch statement.
If you use an earlier vrsion, you need to use several if statements.
As for the Scanner, you can read this tutorial to get started and have a look at this example.

Categories