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.
Related
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.
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);
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.
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.