What expression would I use to stay in this switch statement? - java

I have the pieces that work which is the final total of the burgers, however I can't seem to keep the loop going so that if I select 1 it, grabs the burger and ask me to select again, adding more to the total. When I'm done it exits out and shows the final total and if I press 2. And other number it states in the loop and ask me again.
I don't know what to put into the switch statement to keep it going. Based on what I have I tried I tend to get the statement: "Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted"
Based on what I have so far, I'm stuck.
boolean valid = true;
do {
System.out.println("Select an Option: ");
int userInput = scnr.nextInt();
switch (userInput <=2) {
case 1:
burgerOrder++;
subTotalBurgers = burgerPrice * burgerOrder;
finalSubTotal = burgerPrice * tax;
finalBurgerTotal = burgerPrice + tax;
break;
case 2:
System.out.println("2. Exit");
valid = true;
default:
System.out.println("Sorry");
continue;
}
}while(!valid);
System.out.println("BurgerOrder is " + finalBurgerTotal);

switch (userInput). The <= 2 is making it a boolean expression and is not necessary since you have a default case. Your loop requires that valid have an initial value of false (since that is your loop condition). And, you missed a break in case 2.
boolean valid = false;
do {
switch (userInput) {
case 1:
burgerOrder++;
subTotalBurgers = burgerPrice * burgerOrder;
finalSubTotal = burgerPrice * tax;
finalBurgerTotal = burgerPrice + tax;
break;
case 2:
System.out.println("2. Exit");
valid = true;
break;
default:
System.out.println("Sorry");
continue;
}
} while (!valid);

Your continue statement tells the program to break out of the loop. Just delete that.
For what it's worth, your case 2 also falls through to "default"; you might have intended a break statement after case 2.
And whatever you use as an expression for the switch statement is evaluated to see what case to go to -- userInput <= 2 seems unlikely for values of 1 and 2.

Related

Why isn't my output showing after my switch statement

I'm learning Java right now and I've never used switch statements before. I tried to enter a simple charmed quiz, but something in the switch statement isn't working.
I've tried putting text at various points in the program to test if the program every reaches that code. I have a good response inside the actual switch, so If I answer Question 1 wrong the text prompt will show up. But any later than inside the switch statement and none of my scoring output appears until all iterations of the for loop are complete. I have tried moving the "correct/incorrect" output to various points and none of them seem to work.
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter your name!");
String name = myScanner.nextLine();
int wrongCounter = 0;
boolean correctChecker = false;
int score = 0;
String answer;
System.out.println("Welcome to the Charmed Quiz, " + name + "!");
for (int i = 0; i < 10; i++) {
if (wrongCounter < 4) {
switch(i) {
case 0:
System.out.println("Who read the spell that gave the Charmed Ones their powers?");
System.out.println("Enter your answer");
answer = myScanner.nextLine();
switch (answer) {
case "Pheobe":
correctChecker = true;
break;
default:
correctChecker = false;
break;
}
case 1:
System.out
.println("Who travelled to a cursed town with Prue when Pheobe was shot in a premonition?");
System.out.println("Enter your answer");
answer = myScanner.nextLine();
switch (answer) {
case "Cole":
correctChecker = true;
break;
default:
correctChecker = false;
break;
}
}
if (correctChecker == true) {
score++;
System.out.println("Correct!");
} else {
wrongCounter++;
System.out.println("Incorrect!");
}
This definitely isn't the best way of achieving a quiz game, but if you're using this as a learning exercise then the best course of action is to take the advice from #rzwitserloot.
Add a break after your main switch statement cases as opposed to the inner switch statement.
There is no real use having an inner switch statement though when you can use correctChecker = "Pheobe".equals(answer); to get a true or false boolean value in a single line.
This just means you can avoid the second switch statement which makes it way less confusing.
Altogether your cases could look something like this:
case 0:
System.out.println("Who read the spell that gave the Charmed Ones their powers?");
System.out.println("Enter your answer");
answer = myScanner.nextLine();
correctChecker = "Pheobe".equals(answer);
break;
}
In future, it would be better to store questions and answers in an array and use the for loop to iterate through that. This is a good tutorial on the subject.
Good luck with the rest of your project!
There are many, many problems with this code. The primary issue is that break breaks the closest construct it can break, which in your case is the inner switch. Whereas your intent is clearly to break out of both. Either [A] add another break right before the case 1: statement, or [B] use a labelled break; put something like outer: before the first (primary/outer) switch, and then make all those statements break outer;.
But, really, none of this (either the outer or the inner) are in any way sensible in switch form. I get that this is a learning exercise, but I'd think of something else to learn with.
Also, it's Phoebe, not Pheobe.

Ask for input again if wrong input is entered

I am new to Java programming. I want the program to ask for input again if wrong input is entered by the user. What must I do? Please help! Jump to the 'if else if' part if you want to avoid the mess... And not being rude but please don't request for closing the question if you can't answer.
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
}
else
{
System.out.println("Invalid input.");
}
It has been 28 days since you asked your doubt so I don't know if you have come across the answer or not but here's my solution.
To accept the correct input you need to make use of a while loop, loops are iterations in java which run for multiple number of times as per the given instructions. In this program I have incorporated a while loop whose condition is true always, so basically it is an infinite loop. If the inputted variant is correct and matches with any one of the if condition then the loop will break automatically because of the "break;" statement.
break; is a jump statement in java which allows you to terminate a loop when your requirements are met.
Given below is your required program code.
Hope this solves you query :)
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
while(true)
{
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
break;
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
break;
}
else
{
System.out.println("Invalid input.");
System.out.println("Please enter the variant again:");
}
}

How do I keep looping in a do-while loop as long as the default part of a switch triggers?

What I am trying to accomplish: when the user types in anything other than 1 or 2, there will be a prompt saying "I don't understand you" and it would ask the user to choose 1 or 2 again without having to run the program each time.
Something like this:
do {
String a = input.nextLine();
num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
break;
case 2:
System.out.println("goodbye");
break;
default:
System.out.println("I don't understand you");
}
} while (num == default);
I know typing this will give me an error, so how do I compare it?
First, you have a potential infinite loop because the value for num which controls the stoping condition is never updated inside the loop.
Second, you could introduce a local variable to track when the user input was understood and exit the loop on that condition:
boolean understood;
do {
understood = false;
String a = input.nextLine();
int num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
understood = true;
break;
case 2:
System.out.println("goodbye");
understood = true;
break;
default:
System.out.println("i dont understand u");
break;
}
} while (!understood);
What you asked is technically a while(true) since everything which is not 1 or 2 is default. Also you should probably put your scanning bit in the loop.
If you try to check if value is different from 1 and 2 to ask again for a valid option:
do
{
// stuff
}
while( num != 1 && num != 2)
Since "default" is a keyword you just can not compare it to anything. It's meaningless though, because in your condition you used all possible cases(case 1 and case 2), so your code will never end, printing either "hello" or "goodbye" forever.

Changing an if else statement to a switch statement

I was wondering what would be the best way to convert this if statement within a do while loop to a switch statement within a do while loop.
What would be a better way to tighten up this code?
do{
currency = keyboard.nextInt();
if (currency == 1)
{
sterling = euros * 0.79;
System.out.printf("£ %.2f", sterling);
}
else if (currency == 2)
{
usDollars = euros * 1.28;
System.out.printf("$ %.2f", usDollars);
}
else if (currency == 3){
auDollars = euros * 1.44;
System.out.printf("$ %.2f", auDollars);
}
else{
System.out.printf("Invalid Option");
}
System.out.printf("\nWould you like to go again");
System.out.printf("\n1. Yes\n2 No");
repeat = keyboard.nextInt();
if (repeat == 2){
System.out.printf("Exit Program");
System.exit(0);
}
}while(repeat == 1);
For your example, if statement and switch will do exactly the same things. No differences.
What you could change from your code would be the last if statement:
if (repeat == 2){
System.out.printf("Exit Program");
System.exit(0);
}
You can write this if statement outside the do while, and like this will be checked only once.
Switch case looks something like this
switch (currency) {
case 1: System.out.printf("£ %.2f", euros * 0.79);
break;
case 2: .
.
.
.
.
.
.
case n: .
break;
default: System.out.printf("Invalid Option");
break;
}
Its no different even if it is in a loop (for, while, do while)
Read more about the Switch statement and try to complete the code yourself
On a side note, no need to create variables (sterling,usDollars,auDollars) to store the values of the expressions euros * 0.79 unless you are using storing for later use which doesn't seem to be the case.
You could put the conversion rates in an array, then use what would have been the
switch/if variable to index that array. Something like:
float[] rates = {0.79f, 1.28f, 1.44f};
answer = euros * rates[currency-1];
System.out.printf("$ %.2f", answer);
Then you don't need the selection statement(s). In general, if you see a lot of structural repetition, look for the common code and try to factor it out.

JAVA: Menu Infinite-loop

This is a follow up to a question I have asked previously that did get answers that should have fixed my problem, but unfortunately did not. My program reads in a text file and organises data before giving the user a number of options. When the program gets to this point I want to user to be able to select an option, that performs an operations, but then returns the user back to the start point to be able to perform more operations. This is the answer I liked best (thanks to Octopus) and am currently trying to implement.
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
}
As I see it, the program should enter the loop initially, allow the user to input a selection, then return back to "enter a value". However, the program does not return, and terminates after one operation. How can I prevent this to continue the program running infinitely?
Thanks in advance!
The current while loop is there to get valid input -- don't change it.
You need to wrap this code in another while loop that loops til a sentinal value is entered.
while (!isSentinalValue) {
while (inputNotValid) {
// get valid input
}
}
Edit
More specifically in pseudocode:
while (!isSentinalValue) {
input = invalidValue
while (inputNotValid) {
getInput
}
use input to do menu things
}
So I would not have the switch block inside of the inner loop, since that loop concerns itself only with making sure that the input entered is valid. Do the switch block outside of the inner loop, and be sure to set the sentintal value that allows the user to escape the outerloop when appropriate.
Your while(choiceentry < 1 || choiceentry > 3) condition is wrong. If you want it to loop , then you have to make it between 1 and 3 .
So this also means that you will have to change your choiceentry initialization value. This will work.
int choiceentry = 1
while(choiceentry >=1 && choiceentry <= 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
....
}
your loop only runs while choiceentry is less than 1 or greater than 3. As soon as the user enters one of those values, the loop exits.
Learn to use a debugger.
place the following code after switch
if(choiceentry == 4){
break;
}
Now when you will input 4 then it will be terminated, you can use any value other then 4
Use break only when user wants to quit(Say when choiceentry=0). You can use "continue" to make loop infinite. Sample code is given for reference
int choiceentry = 1; // can set any int value except 0 (exit code is 0 for this example)
Scanner scanchoice = null;
while (choiceentry != 0) {
System.out.println("Enter \"1\", \"2\" or \"3\" ..Press 0 to quit");
scanchoice = new Scanner(System.in);
if (scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
// System.out.println("choiceentry=" + choiceentry);
switch (choiceentry) {
case 0:
{
System.out.println("Bye Bye");
break;
}
case 1:
{
System.out.println("In Case 1");
continue;
}
case 2: {
System.out.println("In Case 2");
continue;
}
case 3: {
System.out.println("In Case 3");
continue;
}
}
}

Categories