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);
Related
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());
I've ran into a weird issue.
I'm trying to make this code loop constantly until the user enters 4; when the user enters 4, I want to make it so that 'Quit_Detect' is set to false.
For some reason, it doesn't let me do that. The code still continuously loops until it is stopped manually.
Below is all of the code that I have used for this program along with some comments.
import java.util.Scanner; // Imports the scanner utility.
public class Start {
public static void main(String[] args) {
Scanner Reader = new Scanner(System.in); // Creates a new scanner.
#SuppressWarnings("unused")
boolean Quit_Detect;
Quit_Detect = true;
while (Quit_Detect = true)
{
int input; // States that input will have a datatype of 'int', or integer. Or, a whole number.
System.out.println("Please input your option.");
System.out.println("1. Door with a crack in it");
System.out.println("2. Normal Wooden Door");
System.out.println("3. Turn around");
System.out.println("4. Quit");
input = Reader.nextInt(); // Has the user define what the variable 'input' will be set to.
switch (input) // Uses the Variable 'input' to detect what case to follow.
{
case 1:System.out.println("First Option");
break;
case 2:System.out.println("Second Option");
break;
case 3:System.out.println("Third Option");
break;
case 4:Quit_Detect = false;
break;
default:System.out.println("Invalid option."); //Prints this if the user inputs any number other than 1, 2, or 3.
}
}
}
}
You should use:
while (Quit_Detect)
instead of:
while (Quit_Detect = true)
The first statement checks if Quit_Detect is true where the second sets the value of Quit_Detect to true.
First thank you for reading. Also I'm very aware of how I can get this to work they way I want it to. I'm just experimenting and not getting expected results.
When I run this code I would expect that when I enter the letter X I would be asked
to try again and re-attempt to enter the letter B. Well, I am. However The program will then break to the start: label and process based on the new value of input we got in the
default case. If on my second attempt I enter the letter B, nothing gets executed in the
switch statement. If you enter the letter B on your second try, the program will print that you entered B and then the program will terminate. Why is this?
import java.util.Scanner;
public class Help
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the letter B: ");
char input = kb.nextLine().charAt(0);
start:
switch(input)
{
case 'B':
System.out.println("Nice Work!");
break;
default:
System.out.println("Try again: ");
input = kb.nextLine().charAt(0);
System.out.println(input);
break start;
}
}
}
The labeled break statement is meant for terminating loops or the switch statement that are labeled with the corresponding label. It does not transfer control back to the label. Your switch statement is simply falling through to the end of program, as it should.
A labeled break would only be helpful if you had nested switch statements and needed to break out of the outer one from the inner one.
See this for further information.
Use while cycle:
import java.util.Scanner;
public class Help
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the letter B: ");
while(true)
{
char input = kb.nextLine().charAt(0);
switch(input)
{
case 'B':
System.out.println("Nice Work!");
break;
default:
System.out.println("Try again: ");
}
}
}
}
I'm making a school assignment and this time around I thought about using a switch statement since it looked more efficient.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
This is my code for the entire class so far:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
private int option;
public static void main(String[] args) {
Test t = new Test();
t.start();
t.optionMenu();
}
public void start() {
System.out.println("Make your choice:");
System.out.println("1: Play");
System.out.println("2: Options");
System.out.println("3: Exit");
}
public void optionMenu() {
try {
Scanner sc = new Scanner(System.in);
this.option = sc.nextInt();
System.out.println(this.option);
} catch (InputMismatchException e) {
System.out.println("Please enter a number");
optionMenu();
}
switch (this.option) {
case 1:
System.out.println("Game starting...");
break;
case 2:
System.out.println("Loading options");
break;
case 3:
System.out.println("Game exiting...");
System.exit(0);
break;
default:
System.out.println("Enter a valid number (1, 2 or 3");
break;
}
}
}
Any help would be much appreciated, thanks!
When you call sc.nextInt() without first asking if (sc.hasNextInt()), you are open to some strange behavior when end-users start typing unexpected input, such as letters. In this case the scanner would not advance its reading pointer, so your program will get stuck reading the same incorrect output.
To fix this issue, add a loop that "clears out" the invalid entry before attempting to read an int again, like this:
while (!sc.hasNextInt()) {
System.out.print("You need to enter an integer.");
sc.nextLine(); // Clear out the bad input
}
int val = sc.nextInt(); // At this point we know that sc.hasNextInt(), because that's the loop condition
Another point is that it is not a good idea to do with recursion what can be done with iteration: the recursive call to optionsMenu is going to accumulate as many levels of invocation as the number of times the end-user enters an incorrect value, so a very persistent user could theoretically force a stack overflow on your program by entering invalid data repeatedly.
Using the code fragment above would free you from the need to call optionsMenu recursively, and also from catching the input exception.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
I'm not sure what you mean here. Firstly, your idea works, this code should be fine!
Second, if you enter anything besides just the number 1, 2, or 3, you will go to the "default:" block of code. Since you are prompting the user again if they fail, typing "a" or "a1" into the prompt just shows the menu again. The user needs to just type "1", "2", or "3" to successfully select a menu option.
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.