I want to use a switch statement to check a range of numbers I have found a few places saying something like
case 1...5 or case (score >= 120) && (score <=125) would work but I just somehow keep on getting errors.
What I want is if the number is between 1600-1699 then do something.
I can do if statements but figured it's time to start using switch if possible.
On the JVM level switch statement is fundamentally different from if statements.
Switch is about compile time constants that have to be all specified at compile time, so that javac compiler produces efficient bytecode.
In Java switch statement does not support ranges. You have to specify all the values (you might take advantage of falling through the cases) and default case. Anything else has to be handled by if statements.
If you really want to use switch statements — here is a way to create pseudo-ranges with enums, so you can switch over the enums.
First, we'll need to create the ranges:
public enum Range {
TWO_HUNDRED(200, 299),
SIXTEEN_HUNDRED(1600, 1699),
OTHER(0, -1); // This range can never exist, but it is necessary
// in order to prevent a NullPointerException from
// being thrown while we switch
private final int minValue;
private final int maxValue;
private Range(int min, int max) {
this.minValue = min;
this.maxValue = max;
}
public static Range from(int score) {
return Arrays.stream(Range.values())
.filter(range -> score >= range.minValue && score <= range.maxValue)
.findAny()
.orElse(OTHER);
}
}
And then your switch:
int num = 1630;
switch (Range.from(num)) {
case TWO_HUNDRED:
// Do something
break;
case SIXTEEN_HUNDRED:
// Do another thing
break;
case OTHER:
default:
// Do a whole different thing
break;
}
You can use ternary operator, ? :
int num = (score >= 120) && (score <=125) ? 1 : -1;
num = (score >= 1600) && (score <=1699 ) ? 2 : num;
switch (num) {
case 1 :
break;
case 2 :
break;
default :
//for -1
}
As far as I know, ranges aren't possible for switch cases in Java. You can do something like
switch (num) {
case 1: case 2: case 3:
//stuff
break;
case 4: case 5: case 6:
//more stuff
break;
default:
}
But at that point, you might as well stick with the if statement.
Related
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!
I have written my code that is a linked list using stacks. The program, that takes an infix form and converts it to postfix, is currently outputting (with the use of my input and output files) the correct conversions. However, I don't understand how to get the evaluatePostFix method to work properly. My problem is printing out false results and I don't know why. Any help is appreciated!
My current evaluatePostfix method:
public static int evaluatePostfix(String postfix) {
Stack<Integer> stack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
int count = 0;
int operandTwo = '0';
int operandOne = '0';
while (count < postfix.length() && count >= 0) {
char nextCharacter = postfix.charAt(count);
switch(nextCharacter) {
case '^':
operatorStack.push (nextCharacter);
break;
case '+':
stack.push(operandTwo + operandOne);
case '-':
stack.push(operandTwo - operandOne);
case '*':
stack.push(operandTwo * operandOne);
case '/':
stack.push(operandTwo / operandOne);
int result1 = nextCharacter;
stack.push(result1);
break;
default: break;
} //End switch
count = count + 1;
} //End while
//return stack.pop();
return stack.peek();
} //End evaluatePostfix
case '+':
stack.push(operandTwo + operandOne);
case '-':
stack.push(operandTwo - operandOne);
You will want to have a break statement in there to avoid falling into the next case block.
You will want to pop these two operands off your stack first, otherwise you don't get to access their values (and they remain on the stack, too).
In general, to debug this kind of code, useful tools are stepping through with a debugger, inserting println statements, writing unit tests and reasoning about the flow and variable state on a piece of paper.
is it considered bad practice to write a switch case statement with a comma such as this:
switch(name)
{
case 'a', 'A' :
break;
}
Rather than
switch(name)
{
case 'a':
case 'A':
break;
}
Just curious as my code seems to run fine either way but I want to get into the habit of using the proper/most accepted way.
It's not bad practice. In fact, it's considered concise and time-efficient.
Take a look at the following code that you have
switch(name){
case 'a', 'A' :
break;
}
The equivalent without using commas would be:
switch(name){
case 'a':
break;
case 'A':
break;
}
And the if-else equivalent would be:
if(name=='a'){
//Do something
}else if(name=='A'){
//Do something
}
Of these, the first example took a mere 36 characters to type. The latter took 49, and the last one took 37 characters.
Moral? Using the comma is definitely more concise and time-efficient that using two cases with a single result. Even the if statements would be more concise.
CheckStyle, the defacto standard for java style, has no check for this.
Do whatever is easiest to read.
I would say though use only one style or the other in any given switch statement.
From JavaDocs:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
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.
My teacher asked me a question and I was really confused how to write it out as a code. I understood what I had to do, but just couldn't write in Java. So the question was that: Design and implement an application that determines and prints the number of odd even and zero digits. Input could be anything from the user/keyboard. I just don't know how to start. So can someone help me here with an answer and an explanation with that?(without using string)
Thank you so much for your time.
Application? It's three lines:
int odds = str.replaceAll("[^13579]", "").length();
int evens = str.replaceAll("[^2468]", "").length();
int zeroes = str.replaceAll("[^0]", "").length();
If the input is not a string, make it one:
long number;
String str = number + "";
I would use a for loop to traverse the input string. Within the for loop would be a switch statement that increments either the 'odd' variable, the 'even' variable,' the 'zero' variable, or does nothing.
This way the string is only traversed once instead of three times.
The code would look something like:
int numOdds = 0;
int numEvens = 0;
int numZeroes = 0;
for(int i = 0; i < inputString.length(); i++) {
switch(inputString.charAt(i)) {
case '1':
case '3':
case '5':
case '7':
case '9': numOdds++;
break;
case '2':
case '4':
case '6':
case '8': numEvens++;
break;
case '0': numZeroes++;
default: break;
}
}
Looks like you have a couple answers. Here is another you may like more because you probably can understand it:
int odds, evens, zeroes;
public void setOddsEvensZereos(String str) {
for(char c:str) {
try {
int i = Integer.parseInt(c + "");
if(i == 0)
zereos++;
else if(i % 2 == 0)
evens++;
else
odds++;
} catch (Exception e){/*the character isn't a number*/}
}
}