Changing an if else statement to a switch statement - java

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.

Related

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:");
}
}

Problem to validate the input from the user in java calculator

So I'm writing a code for a calculator in Java as a homework and I wanted to include an else statement in the end where if the user didn't input a valid operator, you get an error msg. Problem is that even when I input a valid operator, it prints the result and then the else error msg. Any help would be appreciated.
public class Main {
public static void main(String[] args){
Scanner inputi=new Scanner(System.in);
double num1,num2;
char operator;
System.out.println("Please enter the first number: ");
num1=inputi.nextDouble();
System.out.println("Please enter the second number: ");
num2=inputi.nextDouble();
Scanner oper=new Scanner(System.in);
System.out.println("Please enter the operator, the operators are +,-,*,/,%");
operator = oper.next().charAt(0);
if(operator== '+') {
System.out.println("The sum of these numbers is: "+(num1+num2));
}
if(operator=='-') {
System.out.println("The diff of these numbers is: "+ (num1-num2));
}
if(operator=='*') {
System.out.println("The result of this multiplication is: "+(num1*num2));
}
if(operator=='/') {
System.out.println("The division is: "+(num1/num2));
}
if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
else {
System.out.println("Please just pick an operator..");
}
}
}
I'd recommend using switch instead:
switch (operator) {
case '+':
System.out.println("+");
break;
case '-':
System.out.println("-");
break;
/* Other operators */
default:
System.out.println("Please just pick an operator..");
}
You have "if if if if else" you want "if else if else if else". Your one else currently only applies to the if (operator == '%')
Try 'else if':
if(operator== '+') {
System.out.println("The sum of these numbers is: "+(num1+num2));
}
else if(operator=='-') {
System.out.println("The diff of these numbers is: "+ (num1-num2));
}
else if(operator=='*') {
System.out.println("The result of this multiplication is: "+(num1*num2));
}
else if(operator=='/') {
System.out.println("The division is: "+(num1/num2));
}
else if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
else {
System.out.println("Please just pick an operator..");
However, a switch statement would be clearer:
switch(operator) {
case '%':
System.out.println("The module is: "+(num1%num2));
break;
default:
System.out.println("Please just pick an operator..");
}
The problem here is that you are not fully understanding the if else-if else statements.
The "If" means: if this conditional statement is true then execute the code to follow in the brackets.
The "If-else" means: if the statements above (if and else-if) are not true then execute this code.
The "else" means: if the preceding statement above (if or else-if) are not true then execute this code.
Given this, I'm sure not that you can see your error. All of your "if" statements are evaluating to if this condition then do this. Whereas you really wanted, to use "else-if" where if this is true then only execute the following code with the exclusion of the rest of the conditionals. You are correct in having an else clause pick up the default, however since you are not using "else-if" it really is compiling down to if this statement is not true, (the statement right before your else clause):
if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
Then execute the else statement, which is not what you want.
I would recommend really figuring out what your code actually compiles down to in terms of machine instructions.

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

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.

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.

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