How can I not repeat the same case after I use it - java

So, I made a burger class with a method for extra stuff, my question is how can I use case 0,1,2 only 1 time, like if I use case 0, I can't use it anymore, I can use only 1 and 2, If I use case 1 after 0 , then I can use only case 2 since I used case 0 and 1 before , It's possible to do something like that ? If yes how ?
The code:
boolean flag=true;
while(flag){
System.out.println("Enter your choice for extra toppings ");
int choice=scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 0:
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
case 1:
double bacon=1.05;
setAdditional(getAdditional()+bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries=0.79;
setAdditional(getAdditional()+fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag=false;
}
}
} ```

boolean flag = true;
Set<Integer> set = new HashSet<>();
while (flag) {
System.out.println("Enter your choice for extra toppings ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
if (!set.contains(choice)) {
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
}
else {
System.out.println("Added already");
}
continue;
case 1:
double bacon = 1.05;
setAdditional(getAdditional() + bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries = 0.79;
setAdditional(getAdditional() + fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag = false;
}
set.add(choice);
}
}
so I did it with Set in the end, only for salad, but it's the same for the rest, if someone else needs it.

your cases go by integer numbers, so an array of boolean with 1 element for every option.
boolean[] allowed = new boolean[options]; (faster than hasMap of string to boolean).
add a check just before the "switch" statement:
if(allowed[choice] && choice != 3) {...}
you should also create an integer constant STOP_OPTION or something like that and use it in the above if-statement and in the final "case" of your switch statement. in your example, set it to 3. then later you can change it without replacing all instances of "3" in your code. but that's more of a styling suggestion.
the "flag" boolean is also redundant, the while loop can just check if choice != 3. be careful of NumberFormatExceptions!
good luck!

Related

How to create a program that converts binary to decimal

I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?
i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.
package Calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("(2) Convert binary to decimal");
System.out.println("\n\n Please enter your choice: ");
int choice = scan.nextInt();
if(choice == 2){
scan.nextLine();
//prompt for user input
System.out.println("Please enter a binary number: ");
String binary = scan.nextLine();
char[] binaryArray = binary.toCharArray();
int i=1;
int integer=0;
//potential problem somewhere around here?
while(i<8){
if(binaryArray[i]==0) {
++i;
}else if(binaryArray[i]==1) {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
}
System.out.println("The decimal value of the binary number is: "+ integer);
scan.close();
}
}
}
The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.
This is happening because you are reading the input, and converting into an array of char.
Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.
while(i<8){
if(binaryArray[i]=='0') {
++i;
}else if(binaryArray[i]=='1') {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.
Other problems:
Your i starts at 1, so you miss the most significant bit;
You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.
This doesn't work unless you enter exactly 8 bits.
You can write the entire while loop in a much more concise way:
for (int i = 0; i < binaryArray.length; i++) {
integer *= 2; // shift the digits along by 1 place
if (binaryArray[i] == '1') {
integer += 1; // set the least significant bit.
}
}
You should get away from all those switch statements.
Say you have "10101101" as input.
set val = 0;
Then either multiply by val by 2 or shift left 1 bit. They're the same. It is important
you do this before adding the next bit.
Start from the left and if it's a '1', add a 1 to val. Otherwise, add 0.
Then repeat starting at multiply until you've gone thru the string.
val should then have the decimal version when you print it.

query about switch function in java

Scanner input = new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z = input.nextInt();
switch (z) {
case 1:
System.out.println("your result is" + (x + y));
break;
case 2:
System.out.println("your result is" + (x - y));
break;
case 3:
System.out.println("your result is" + (x * y));
break;
case 4:
System.out.println("your result is" + (x / y));
break;
default:
System.out.println("choose the option from listed above");
break;
}
above code is for calculator in switch...
query is :
how can i call the switch function again in default case ?
Well, you can't execute the switch statement again because that does not solve the problem. z's value does not change, so it will always go to the default branch no matter how many times you re-execute the switch.
I suggest to put the whole thing in a loop and break out of the loop for cases 1-4.
loop:
while (true) {
Scanner input=new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z=input.nextInt();
switch(z)
{
case 1 :
System.out.println("your result is"+(x+ y));
break loop;
case 2 :
System.out.println("your result is"+(x- y));
break loop;
case 3 :
System.out.println("your result is"+(x* y));
break loop;
case 4 :
System.out.println("your result is"+(x/ y));
break loop;
default :
System.out.println("choose the option from listed above");
break;
}
}
Note that I wrote break loop instead of break. break will just break out of the switch statement. This is why I added a label loop: before the loop starts, so that I can break out of the loop, instead of the switch, later.
Some corrections of your terminology
In Java, there are technically no functions. Functions must be outside of a class. There are only "methods" in Java. They look like this:
public static void someMethod(int somePar) { }
switch is neither a function nor a method, so you can't "call" it. switch is a control structure that is "executed" or "run".
You can do like this:
public void promptUser(){
Scanner input=new Scanner(System.in);
boolean validOption = false;
while(!validOption){
validOption = true;
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z=input.nextInt();
switch(z){
case 1 :
System.out.println("your result is"+(x+ y));
break;
case 2 :
System.out.println("your result is"+(x- y));
break;
case 3 :
System.out.println("your result is"+(x* y));
break;
case 4 :
System.out.println("your result is"+(x/ y));
break;
default :
System.out.println("choose the option from listed above");
validOption = false;
break;
}
}
}
I prefer using a loop so you won't be stacking a lot of calls to the same method over and over, thus you can avoid OutOfMemoryError.
Let's assume your code is in a function called calculate()
There are a few ways you could do this.
Recursively:
Just call the function again in the switch.
default :
System.out.println("choose the option from listed above");
calculate();
return;
Return a value and loop:
Change the function so it returns a value. For example, return true if is does anything but default, and false if it hits default. Then, in the logic that calls calculate(), put it in some sort of loop.
bool doLoop = true;
while (doLoop)
{
doLoop = !calculate()
}
You could put it inside a loop, for example a do ... while loop, and you may capture a key as ending condition.
do {
// your code here
} while(ending_condition);
while(true)
{
Scanner input=new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/ \n5-->Exit");
int z=input.nextInt();
switch(z)
{
case 1 :
System.out.println("your result is"+(x+ y));
break;
case 2 :
System.out.println("your result is"+(x- y));
break;
case 3 :
System.out.println("your result is"+(x* y));
break;
case 4 :
System.out.println("your result is"+(x/ y));
break;
case 5 :
System.exit(0);
default :
System.out.println("choose the option from listed above");
break;
}
}

.hasNextInt() in switch statement

I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.
I want it so that if anything other than an integer is entered it will go to default in the switch.
Any help would be great. Thanks!
while(loop && kb.hasNextInt())
{
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
default :
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
If the next input is not an integer,
then .hasNextInt() will return false,
and therefore the loop will terminate early.
If you want to allow text input and respond to it,
then you need to read line by line, text instead of numbers,
and parse the line read with Integer.parseInt.
If the line cannot be parsed, you will get a NumberFormatException.
You can catch it, and handle appropriately.
while (loop && scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
choice = Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("That is not an integer. Please try again!");
continue;
}
switch (choice) {
case 1:
language = "FRENCH";
loop = false;
break;
case 2:
language = "GERMAN";
loop = false;
break;
case 3:
language = "SPANISH";
loop = false;
break;
default:
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.
Example (using a while loop instead of if statement to really try getting the number):
while(loop)
{
// validate int using while loop
while(!kb.hasNextInt())
{
System.out.println("you must enter a number! ");
kb.next();
}
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
}
}
System.out.println("Thank You " + studentID + " you have been registered for " + language);
This code will blow before it even begins if the user did not enter a number as the while required kb.hasNextInt() to be true (have a number) to even run.
What I do is that I usually put the validation around where I receive the input:
int choice;
Boolean retry = null;
while(retry == null) {
try{
String input = scanner.nextLine();
choice = Integer.parseInt(input);
retry = false;
}catch(NumberFormatException e){
System.out.println("Please enter a number from 1 to 4.");
}
}
switch(choice){
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
case 3:
// Do stuff
break;
case 4:
// Do stuff
break;
default:
System.out.println("Something went wrong!");
}

how to make a loop of a switch statement with a label in java

it's quite simple but i don't seem to fegure it out
here is my code
System.out.println("1=>do this \n2=> do that \n3=> blablabla \n4=> EXIT");
choose:{
int choix = s.nextInt();
switch (choix) {
case 1 : lper.addpersonne();
break choose;
case 2 : lper.removepersonne();
break choose;
case 3 : blalalalala
when it comes to execution
the "lper.addpersonne" works perfectly fine but after that i can't get the label where i can choose something else . it just stops
Why not clean that code up a bit and use something along these lines?
int choix;
do {
System.out.println("1=>do this \n2=> do that \n3=> blablabla \n4=> EXIT");
choix = s.nextInt();
switch (choix) {
case 1 : lper.addpersonne();
break;
case 2 : lper.removepersonne();
break;
case 3 : blalalalala
break;
} while (choix != 4);
This way you don't have to worry about the for loop, it repeats until the user wants to quit, and you don't have to use the pesky labels.
boolean loop = true;
while(loop){
System.out.println("1=>do this \n2=> do that \n3=> blablabla \n4=> EXIT");
choose:{
int choix = s.nextInt();
switch (choix) {
case 1 : lper.addpersonne();
break choose;
case 2 : lper.removepersonne();
break choose;
case 3 : blalalalala
.... //What do you want more
}
if(choix == 4){loop = false;}
}
}

Switch statement + user input

Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}

Categories

Resources