Java why wont scanner work inside a switch - java

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(" ");

Related

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());

Java: nextLine() skipping input and adding blank spaces to arrayList [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I have this piece of code that is supposed to add String values to an arrayList through the Scanner's next() or nextLine() method. The problem with next() is that it ignores everything after the first white space so I get that I should use the nextLine() method instead. The problem with nextLine() is that that it doesn't record the input, instead it stores a couple of blank spaces into the arrayList. Here's the code:
System.out.println("\nWhat is your idea? ");
String i = in.nextLine();
in.nextLine();
meals.add(i);
System.out.println("\n" + i + " has been entered into the idea pool. \n");
System.in.read();
I added the extra "in.nextLine()" after the initial "String i = in.nextLine()" because that's the only fix I found when I researched this problem but it doesn't work for me, it just still just stores a couple of blank spaces. Also, the System.in.read(); at the end there is only there so that it doesn't just jump forward after taking the input.
Here is the code where the above sample fits into:
ArrayList<String> meals = new ArrayList<String>();
String select = "";
while(!select.equals("")){
System.out.println("What would you like to do?");
System.out.println("1. <Irrelevant>");
System.out.println("2. Enter an idea");
System.out.println("3. <Irrelevant>");
System.out.println("4. <Irrelevant>");
System.out.println("Q. <Irrelevant>");
select = in.next();
switch(select){
case "1":
//Some stuff here.
case "2":
//Here's where the above problem fits into.
case "3":
//More stuff here
//and so on...
}
}
The reason why you are facing such issue is because you are using firstly next() method to read the input, and the further inputs you are taking using nextLine().
next() accepts the input, and the input pointer stays on the same line as of the current input.
So, as soon as you enter your choice and hit Enter, the choice is saved into the select variable, but, the input pointer is still on the same line. You should use a nextLine() to move the pointer to a new line.
Then you should use any number of nextLine()'s to receive multiple lines.
Also, remove an extra nextLine() method call from the case 2 statement. Remove the System.in.read() too, as your problem would have been solved.
ArrayList<String> meals = new ArrayList<String>();
String select = "";
while(!select.equals("")){
System.out.println("What would you like to do?");
System.out.println("1. <Irrelevant>");
System.out.println("2. Enter an idea");
System.out.println("3. <Irrelevant>");
System.out.println("4. <Irrelevant>");
System.out.println("Q. <Irrelevant>");
select = in.next();
in.nextLine(); // add this extra line in your code
switch(select){
case "1":
//Some stuff here.
case "2":
System.out.println("\nWhat is your idea? ");
String i = in.nextLine();
meals.add(i);
System.out.println("\n" + i + " has been entered into the idea pool. \n");
case "3":
//More stuff here
//and so on...
}

Invalid character statement case value in switch statement

My code is telling me that the case 'A+' is an invalid character statement, but I need to be able to have case A+, A, A- and so on. What I'm wondering is: can I not have + or - inside the case value at all? and if so, is there any other way to identify what the user inputs into the console. I haven't been able to find an answer browsing around. Help is appreciated!
import java.util.Scanner;
public class GradeAdvice {
public static void main(String[] args) {
// User will input grade and program will give advice corresponding
// to that grade
// Prompt use for their grade
System.out.println("What was your grade on the midterm?");
char midtermGrade;
// Create an input object
Scanner input = new Scanner(System.in);
midtermGrade = input.next().charAt(0);
// Determine which advice to give based on grade
switch (midtermGrade)
{
case 'A+' :
case 'a+' : System.out.println("Continue doing what you have been doing, ask questions");
break;
default: System.out.println("This grade is invalid.");
break;
}
// Close input
input.close();
}
}
Character literals in Java identify one character, not multiple characters, within single-quotes. For multiple characters, you must use a String, delimited by double-quote characters.
In Java 7+, you can use Strings as case labels, e.g.
case "A+":
But you are only using the first character of input. Change
char midtermGrade;
midtermGrade = input.next().charAt(0);
to
String midtermGrade;
midtermGrade = input.next();
A char can hold a single character. Instead, you could just use a String:
String midtermGrade;
// Create an input object
Scanner input = new Scanner(System.in);
midtermGrade = input.next();
// Determine which advice to give based on grade
switch (midtermGrade)
{
// Note that strings are denoted by "s, not 's.
case "A+" :
case "a+" : System.out.println("Continue doing what you have been doing, ask questions");
break;
default: System.out.println("This grade is invalid.");
break;
}
Use String, and normalize the case
switch( input.next().toUpperCase() )
{
case "A+" :
...
default :
...
}
"A+", double quotes for string, single quote for character.
This is because you are using a character instead of a string. A character is exactly what it says, one character. A+ is two characters A and +. Use double quotes (") for string literals. For example:
'A' \\ This is a character
"A" \\ This is a string
"A+" is not char , it is string define it as string .
A+ is a string, not a character. You could've done this in C# (using " rather than '), but not in Java, nor most other languages. Simplest way out for you is probably to convert the switch into a series of 'if' statements.

What am I doing wrong with this scanner? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
This is my current code, fairly basic, I'm adding names to an array and deleting said names using scanners. Like I said basic stuff. I'm using a switch since it makes my life 100000x easier than just using a bunch of if's and it's a nicer layout regardless.
The following is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class Account
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
ArrayList list = new ArrayList();
boolean quit = false;
do
{
System.out.println ("MENU\n 0: Enter name to list\n 1: Delete name from list\n 2: Print Current List\n 3: Quit");
int input = sc.nextInt();
switch(input)
{
case 0:
System.out.println ("Enter name to add to list");
list.add(sc.nextLine());
System.out.println("Name has been added");
System.out.println (list);
break;
case 1:
System.out.println("Enter name to remove");
list.remove(sc.next());
System.out.println (list);
break;
case 2:
System.out.println (list);
break;
case 3:
quit = true;
break;
default:
System.out.println ("Invalid choice");
}
}while(!quit);
System.out.println ("Exiting menu");
}
}
My issue is that once I enter 0 to go to the first case, it seems as though it just skips the user entry and outputs an empty string. If I were to do that exact same procedure outside of my switches it seems to work, so it makes me think that something might be up with my scanner. Possibly has something to do with the int scan I made right before to get into the case? But I could have sworn I've done something like this dozens of times...
I should also mention that sc.next() works fine, its just sc.nextLine() that seems to be giving me stress.
When you use a Scanner, if you want to use nextline() after next(), nextInt(), or nextDouble(), you have to put a nextLine() alone before the line where you get input, in order to consume the newline.
Or, to avoid having to account for this problem, instead of using nextInt(), and nextDouble(), just do:
Integer.parseInt(nextLine())//equivalent of nextInt() except no funny errors
Double.parseDouble(nextLine())//equivalent of nextDouble() without funny stuff
This is happening because the nextInt does not read the last newline character of the input, and that remaining newline is getting consumed in the next call to nextLine.
The same behavior can be noticed if we use nextLine after any of the nextXXX except for the nextLine itself
In order to solve this problem you can:
Either use a blank nextLine call after nextInt to consume the newline
int input = sc.nextInt();
sc.nextLine(); // Use this to consume the newline character
String input1 = sc.nextLine();
or you can use the workaround as mentioned by #kirbyquerby

Switchstatement stops reading at white spaces

So I'm having a problem doing an assignment for my java class. The purpose is to create a program that uses a switch statement to convert letters from a string to their phonetics. i.e, A or a becomes Alpha.
The problem I'm having is the switch statement stops reading at the first whitespace in the string. How do i get it to continue reading the string without stopping at whitespaces
(i.e " ")?
Basically user inputs a string "Hi Hi" the output should be "Hotel Indiana Hotel Indiana"
The problem I'm having is it only gives "Hotel Indiana" stopping at the first whitespace i think at least.
This is the code i have so far:(I cut out most of the letters/numbers to save space and kept what i thought was most important for answering the question.)
import java.util.*;
public class SwitchStatement {
/**
* #param args
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter a message: ");
String message = keyboard.next();
for(int i = 0 ; i < message.length(); i++)
switch(message.charAt(i)) {
case 'a':
case 'A':
System.out.print("Alpha");
break;
case 'b':
case 'B':
System.out.print("Bravo");
break;
case ' ':
System.out.print(" ");
break;
default:
System.out.print(message.charAt(i));
break;
}
}
}
Thanks in advance for the help.
String message = keyboard.next(); reads one word at the time of call separated by space (" ").
Use String message = keyboard.nextLine(); to read the whole line including spaces within.
You should use nextLine. If you use next() deliminator comes in to picture which is space char. So eventually you end up reading only one token not full string.
String message = keyboard.nextLine();
e.g For below string
A a B b
keyboard.next()---> will return you A if you again call then B and so on
keyboard.nextLine()-->will return you whole line ie. A a B b which you want

Categories