I'm having trouble transforming the following nested if statement below, into an equivalent switch statement. If anyone can give me some advice, it would be appreciated.
if (num1 == 5)
myChar = ‘A’;
else
if (num1 == 6 )
myChar = ‘B’;
else
if (num1 = 7)
myChar = ‘C’;
else
myChar = ‘D’;
Pretty straightforward, just use the number as the thing you want to switch on. Your else case becomes the default case.
switch (num1) {
case 5:
myChar = 'A';
break;
case 6:
myChar = 'B';
break;
case 7:
myChar = 'C';
break;
default:
myChar = 'D';
break;
}
If the values follow a simple pattern like this, you don't need a switch at all. For example you can do
myChar = num1 >= 5 && num1 <= 7 ? (char) ('A' + num1 - 5) : 'D';
If num1 is always 5, 6, 7 or 8 you can just do
myChar = (char) ('A' + num1 - 5);
For more details chek the documentation : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
switch(num1){
case 5:
myChar = ‘A’;
break;
case 6:
myChar = ‘B’;
break;
case 7:
myChar = ‘C’;
break;
default:
myChar = ‘D’;
}
In JDK 12, extended switch will allow you to assign a char value directly to the switch. Construct your switch as such:
char myChar = switch(num1) {
case 5 -> 'A';
case 6 -> 'B';
case 7 -> 'C';
default -> 'D';
}
Related
My task is write a program to take string as input(only numbers) and for each digit starting from 0 to 9, print the count of their occurrences in the string.
I have completed it. I have declared 10 integers with zero. Each integer will count the corresponding integers. But in the last when I am printing the result it is giving me the result as 48+count
Count represents the number of count of values occurrences.
For the correct result I need to subtract 48. I am unable to understand why I am getting value.
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int a='0',b='0',c='0',d='0',e='0',f='0',g='0',h='0',i='0',j='0';
String s=sc.next();
OUTER:
for (int k = 0; k<s.length(); k++) {
char ch=s.charAt(k);
switch (ch) {
case '0':
a++;
break;
case '1':
b++;
break;
case '2':
c++;
break;
case '3':
d++;
break;
case '4':
e++;
break;
case '5':
f++;
break;
case '6':
g++;
break;
case '7':
h++;
break;
case '8':
i++;
break;
case '9':
j++;
break;
case ' ':
break OUTER;
default:
break;
}
}
System.out.println("0 "+(a-48));
System.out.println("1 "+(b-48));
System.out.println("2 "+(c-48));
System.out.println("3 "+(d-48));
System.out.println("4 "+(e-48));
System.out.println("5 "+(f-48));
System.out.println("6 "+(g-48));
System.out.println("7 "+(h-48));
System.out.println("8 "+(i-48));
System.out.println("9 "+(j-48));
}
}
please anyone explain me what I can do for removing this extra value in this program.
thanks
Instead of
int a = '0'
use
int a = 0
'0' is equal to 48 in ASCII and it is a character, not a number. So by int a = '0', you actually initialize a to 48
I would suggest to use an array instead. it'll be easier to process.
String str = sc.next();
char[] input = str.toCharArray();
int[] count = new int[10]; // stores the count, int array initialized to 0 by default
for(int i = 0 ; i < input.length; i++){
// get index value by substracting ASCII value
int c = input[i] - 48; // 48 being ASCII Value of '0'
count[c]++;
}
// print the count array
System.out.println(Arrays.toString(count));
count[0] has no of 0's
count[1] has no of 1's
.....
It is a pretty standard switch case used within a program that replicates an electric circuit. The main thing I am looking for is easier readability of the code and brevity, without disregarding efficiency.
edit: Didn't realize that I was unclear on the purpose of offset, the way offset works is that it will offset the input char by a number of characters equal to offset which is an integer. So for example if source is 'a' and offset is 2 this will return the value within the paths array at index 2.
char passCurrent(char source)
{
source += offset;
switch(source)
{
case 'a':
return this.paths[0];
case 'b':
return this.paths[1];
case 'c':
return this.paths[2];
case 'd':
return this.paths[3];
case 'e':
return this.paths[4];
case 'f':
return this.paths[5];
case 'g':
return this.paths[6];
case 'h':
return this.paths[7];
case 'i':
return this.paths[8];
case 'j':
return this.paths[9];
case 'k':
return this.paths[10];
case 'l':
return this.paths[11];
case 'm':
return this.paths[12];
case 'n':
return this.paths[13];
case 'o':
return this.paths[14];
case 'p':
return this.paths[15];
case 'q':
return this.paths[16];
case 'r':
return this.paths[17];
case 's':
return this.paths[18];
case 't':
return this.paths[19];
case 'u':
return this.paths[20];
case 'v':
return this.paths[21];
case 'w':
return this.paths[22];
case 'x':
return this.paths[23];
case 'y':
return this.paths[24];
case 'z':
return this.paths[25];
}
return '/';
}
Eliminate the switch and use subtraction after checking the range. Something like,
if (source >= 'a' && source <= 'z') {
return this.paths[source - 'a'];
}
return '/';
And, we can shorten that further with a ternary like
return (source >= 'a' && source <= 'z') ?
this.paths[source - 'a'] : '/';
A char is just a number; the meaning of the number has to do with how characters are laid out in Unicode (the numbers from 0 to 127 were defined a long time ago by ASCII, which got subsumed into Unicode).
Thus, if source is 'a', it actually has the integer value 97. The letters from a to z are all consecutive in Unicode, so b is 98, c is 99, etc.
That means that if you want 0 for a, 1 for b, and so on, you can get it by simple subtraction. Thus:
if (source >= 'a' && source <= 'z') {
return this.paths[source - 97];
}
or, equivalently (and more readably):
if (source >= 'a' && source <= 'z') {
return this.paths[source - 'a'];
}
since 'a' is just another way to write 97.
I need help converting this code into a switch.
if(val >= 0 && val < 10)
cell[0].plus1();
else if(val >= 10 && val < 20 )
cell[1].plus1();
else if(val >= 20 && val < 30 )
cell[2].plus1();
else if(val >= 30 && val < 40 )
cell[3].plus1();
else if(val >= 40 && val < 50 )
cell[4].plus1();
else if(val >= 50 && val < 60 )
cell[5].plus1();
else if(val >= 60 && val < 70 )
cell[6].plus1();
else if(val >= 70 && val < 80 )
cell[7].plus1();
else if(val >= 80 && val < 90 )
cell[8].plus1();
else if(val >= 90 && val < 100 )
cell[9].plus1();
Any help will be highly appreciated.
You don't need a switch statement.
All these statements can be reduced to :
if (val >= 0 && val < 100)
cell[val/10].plus1();
If you really want a switch, you can do:
int v = val/10;
switch(v) {
case 1: cell[1].plus1();
break;
case 2: cell[2].plus1();
break;
case 3: cell[3].plus1();
break;
case 4: cell[4].plus1();
break;
case 5: cell[5].plus1();
break;
case 6: cell[6].plus1();
break;
case 7: cell[7].plus1();
break;
case 8: cell[8].plus1();
break;
case 9: cell[9].plus1();
break;
}
But you could simply do (which is equivalent):
if (val >= 0 && val < 100) cell[val/10].plus1();
Since the cases in a switch statement are determined by equality, an if-else ladder using inequality can not naturally be modelled by a switch statement.
You could list out each of the values in the range and utilize the fall-through nature:
switch (val)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
cell[0].plus1();
break;
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
cell[1].plus1();
break;
...
}
This really is not any improvement to your code and quickly becomes very unwieldy.
Since each of your conditions perform the exact same operation (cell[ X ].plus1()), all you really need is to handle the relationship between the input val and the array index. As Eran's answer shows, in your code this relationship is a simple matter of integer division. I recommend choosing his answer.
int division = val / 10;
now val >=0 && val < 10 equals division = 0
etc...
Why is the output "ADC" and where the D came from ? Also, what is the goal of the default and continue commands in this code?
char x = 'A';
while(x != 'D') {
switch(x) {
case 'A':
System.out.print(x); x = 'D';
case 'B':
System.out.print(x); x = 'C';
case 'C':
System.out.print(x); x = 'D';
default:
continue;
}
You start with A. Since x != 'D' you enter the while loop.
Now the flow is the following:
enter case 'A'
print A and assign x = 'D'
fall-through to case 'B'
print D (since x == 'D') and assign x = 'C'
fall-through to case 'C'
print C (since x == 'C') and assign x = 'D'
fall-through to default (which will normally be reached, when you can't find a matching case)
continue (which means return to the start of the while loop)
Since x == 'D' the condition evaluates to false and won't enter the loop.
==> Result: ADC is printed.
Yes, you forgot the breaks between the steps. So all steps after the matching case will be executed. Try it with:
switch (x) {
case 'A':
System.out.print(x);
x = 'D';
break;
case 'B':
System.out.print(x);
x = 'C';
break;
case 'C':
System.out.print(x);
x = 'D';
break;
}
Switch statements have what is called "fall through".
You need a break at the end of every case, otherwise all of them will run, as is happening here.
char x = 'A'; //starts off as A
while(x != 'D') {
switch(x) {
case 'A':
System.out.print(x); x = 'D'; //here is gets printed and changed to D
case 'B': //you fall through here because there's no break
System.out.print(x); x = 'C'; //print again then change to C
case 'C': //fall through again
System.out.print(x); x = 'D'; //print again then change to D
default:
continue;
You only enter the case if it matches (so if it starts as C it will only print once) but once a match is found you can fall through to the other cases as well.
If you add breaks, then you won't fall through anymore.
char x = 'A';
while(x != 'D') {
switch(x) {
case 'A': //match
System.out.print(x); x = 'D'; //print then modify
break; //break
case 'B':
System.out.print(x); x = 'C';
break;
case 'C':
System.out.print(x); x = 'D';
break;
default:
continue;
look at this switch:
int a = 0;
switch(a) {
case 0:
System.out.println("0");
case 1:
System.out.println("1");
}
The lines of code which are executed are:
int a = 0;
System.out.println("0");
System.out.println("1");
In order to only execute the statement you want to execute you have to use break at the end of every case:
int a = 0;
switch(a) {
case 0:
System.out.println("0");
break;
case 1:
System.out.println("1");
break;
}
When first time switch executes, case 'A' selected, prints A and set x to 'D',
There no break between cases, so next line executes - print D (as x set to 'D' before) and set x to 'C'. And so on.
I have a program where the user inputs 6 doubles, and the program outputs every combination of operators that can go in-between the doubles as 1024 separate strings. Here are the first two results if the user inputed 14,17,200,1,5, and 118:
"14.0+17.0+200.0+1.0+5.0+118.0"
"14.0+17.0+200.0+1.0+5.0-118.0"
What I want to do is perform the arithmetic according to the order of operations. Each double is stored as a variable a through f and each operator in-between these variables is stored as a char a_b through e_f. So:
double a, b, c, d, e, f;
char a_b, b_c, c_d, d_e, e_f;
My first thought was to write the code like this:
public double operateGroup() {
value = 0;
switch (a_b) {
case '+':
value += a + b;
break;
case '-':
value += a - b;
break;
case '*':
value += a * b;
break;
case '/':
value += a / b;
break;
default:
break;
}
switch (b_c) {
case '+':
value += c;
break;
case '-':
value += -c;
break;
case '*':
value *= c;
break;
case '/':
value /= c;
break;
default:
break;
}
switch (c_d) {
case '+':
value += d;
break;
case '-':
value += -d;
break;
case '*':
value *= d;
break;
case '/':
value /= d;
break;
default:
break;
}
switch (d_e) {
case '+':
value += e;
break;
case '-':
value += -e;
break;
case '*':
value *= e;
break;
case '/':
value /= e;
break;
default:
break;
}
switch (e_f) {
case '+':
value += f;
break;
case '-':
value += -f;
break;
case '*':
value *= f;
break;
case '/':
value /= f;
break;
default:
break;
}
return value;
}
But this doesn't work because it is the same as doing (a O b) O c) O d) O e) where O is any arbitrary operator. Any tips?
Since there are no parentheses, a trivial approach will work:
Go through the list once to process multiplications and divisions
When an operator between X and Y is * or /, replace X by X*Y or X/Y, and remove Y; also remove the operator
Now go through the list again, this time processing additions and subtractions in sequence.
To implement this approach, define two lists - the list of N Doubles, and N-1 operators, and implement the calculation as follows:
ArrayList<Double> vals = ...
ArrayList<Integer> ops = ... // 1=+, 2=-, 3=*, 4=/
for (int i = 0 ; i < ops.Count ; i++) {
int op = ops.get(i);
if (op == 3 || op == 4) {
if (op == 3) {
vals.set(i, vals.get(i) * vals.get(i+1));
} else {
vals.set(i, vals.get(i) / vals.get(i+1));
}
ops.remove(i);
vals.remove(i+1);
i--;
}
}
double res = vals.get(0);
for (int i = 0 ; i != ops.Count ; i++) {
if (op == 1) {
res += vals.get(i);
} else {
res -= vals.get(i);
}
}
If you need the operators' and operands' information, you should build a Parse Tree (this has been asked before).
If you are only interested in the result, you can evaluate the String directly:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Eval {
public static void main(String[] args) throws Exception {
ScriptEngineManager s = new ScriptEngineManager();
ScriptEngine engine = s.getEngineByName("JavaScript");
String exp = "14.0+17.0+200.0+1.0+5.0-118.0";
System.out.println(engine.eval(exp));
}
}
Output:
119.0
I would say you should parse it into a tree and then walk the tree to evaluate. Numbers are leaf nodes and operators are parents.