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());
Related
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;
}
}
}
So, I have some code which, when simplified, is this:
import java.util.scanner
private Scanner input;
int enterInteger()
{
System.out.println("Enter the quantity");
return input.nextInt();
}
String enterString()
{
return input.nextLine();
}
void main()
{
System.out.println("Enter option: 1) Add Quantity\n2)Edit Item");
String input = enterString();
switch (input)
{
case "1":
enterInteger();
break;
case "2":
//Do whatever
break;
default:
System.out.println("Invalid!");
main();
break;
}
}
So, whenever the user enters the option as 1, it loads enterInteger() that asked the user, and returns, an integer.
However, when this happens, and the user enters the integer and presses enter, the code then begins executing the default: case. When I add a breakpoint the value of option is "", so that's obviously why the default: executes, but I can't see how to prevent it.
I know it's something dumb, so thank you.
I don't know the reason yet, But in the past I had to work with only nextLine() and parse with Integer.parseInt() when necessary.
By the way, You haven't initialized the Scanner.
Scanner input = new Scanner(System.in);
I have a scanner asking for some preferences. It creates an int variable choice between 0 and 3. Then I do the following:
String location;
switch(choice){
case 0:
System.out.println("Please type the zip codes you would like to search in a comma separated list");
location = input.nextLine();
break;
case 1:
System.out.println("Please type the street names you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
case 2:
System.out.println("Please type the boroughs you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
default:
location = "none";
break;
}
String locations[] = location.split("\\s*,\\s*");
now to me this seems perfectly fine, but when choice is set to 0,1, or 2 it will print the correct line, but skip the part where the user has to input something (the line that looks like location=...)
this means that it does not give the user the chance to enter anything and therefore locations becomes a blank list. Why does this happen and how can I fix it?
You are probably reading the newline after the last input, instead of the really next line. Try:
int choice = input.nextInt();
input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
case 0:
Syst...
The nextInt() call, where you prompt the choice, does not end the line. So the first call to nextLine() after nextInt() is going to return an empty String. To fix that, eat the empty line after the integer and then move on.
I faced the same problem as you. Try:
case 'f' :
System.out.println("Enter a word or phrase to be found:");
scnr.nextLine();
String phrase = scnr.nextLine(); //
Put nextLine after the read before the switch.
System.out.print("Digite um nĂºmero ente 1 e 9: ");
int opc = read.nextInt();
read.nextLine();
switch(opc) {
And read your value with nextLine()
case 6:
String[] procurados = read.nextLine().split(" ");
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.
So far I have written choice as a string but I need to write it to accept int instead of string. The user has to enter 1, 2, 3 and if they enter 1 or 2 the program should continue but if the user enters 3 the program ends.
normally I write the choice as
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
Is there a way to write the code similar to that? I found a way using if statements but that screws up the rest of my code so I'm trying to find a way around that.
Thanks,
it would be better to to this with a so called switch construct
int choice = readInt();
switch(choice){
case 1:
case 2:
// your code
break;
case 3:
// exit code
break;
}
final int STOP_CHOICE = 3;
String choice = "1";
while (Integer.parseInt(choice) != STOP_CHOICE)
{
Note that a non-integer choice will cause Integer.parseInt to throw a NumberFormatException, so you may want to do it somewhere else and catch that possibility.