i want to replace java code using if-else to switch [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i want java code using switch to same execute ? how i can do this by java
if(ave>=90.0)
return 'A';
else if(ave>=80.0)
return 'B';
else if(ave>=70.0)
return 'C';
else if(ave>=60.0)
return 'D';
else
return 'F';

The intuitive solution is: It's impossible.
A switch needs a discreet set of elements. A range of numbers is infinite and you can't do
switch(something) {
case 90.0:
case 90.000000000001:
....
There is a way you could do that though: Convert the range to some number:
private static int toRangeIndex(double d) {
if (d >= 90.0)
return 0;
else if (d >= 80.0)
return 1;
else if (d >= 70.0)
return 2;
else if (d >= 60.0)
return 3;
else
return 4;
}
public static double sumColoumn(double[][] m, int coloumnIndex) {
switch (toRangeIndex(ave)) {
case 0:
return 'A';
case 2:
return 'B';
case 3:
return 'C';
case 4:
return 'D';
default:
return 'F';
}
}
This is obviously not better in your case. But there are cases in which you could use such a technique.

Not possible directly, switch requires exact match.
What you can do is write function like:
int classify(double avg) {
// perform some if-else chain, or loop with test inside, or calculation:
return (int)(avg/10.0);
}
Then use the return value in switch:
switch (classify (avg)) {
case 10: // average of exact 100.0 gives 10, let's not F that...
case 9:
return 'A';
case 8:
return 'B';
//...
default:
return 'F';
}
But, in your specific case it is just moving the if... ladder into a different function, and probably not good idea. So don't do it :-).
Or rather, if you do it, do it because it makes code easier to understand and maintain (and here it in my opinion does not), not because you want to use switch statement.

int findIndex(double ave){
int index=(int)(ave/10.0);
if(index>=9)
return 9;
else
return index;
}
switch (findIndex(ave)) {
case 9:
return 'A';
case 8:
return 'B';
case 7:
return 'C';
case 6:
return 'D';
default:
return 'F';
}

i finded answer
switch(t1)
{
case 100: case 99: case 98: case 97:case 96:case 95:case 94:case 93:case 92:case 91:case 90:
cr='A';
break;
case 89: case 88: case 87: case 86:case 85:case 84:case 83:case 82:case 81:case 80:
cr='B';
break;
case 79: case 78: case 77: case 76:case 75:case 74:case 73:case 72:case 71:case 70:
cr='C';
break;
case 69: case 68: case 67: case 66:case 65:case 64:case 63:case 62:case 61:case 60:
cr='D';
break;
default:
cr = 'F';
break;
}

Related

Converting char to int for in java switch statement [duplicate]

This question already has answers here:
In a switch statement, why are all the cases being executed?
(8 answers)
Closed last year.
I am working on the game where the columns of the board are represented by the characters but i would like to assign them an index.
I have decided to use the switch statement in that case, however it does produce the wrong result.
With the current code I attach, it gives me 14 as an index, however since the string is 7h, and it takes h as a char, it should give an index of 7. What Could be an issue? Thanks in advance!
public class Check {
public int columnToInt(char c) {
int index=0;
switch(c) {
case 'a':
index=0;
case 'b':
index=1;
case 'c':
index=2;
case 'd':
index=3;
case 'e':
index=4;
case 'f':
index=5;
case 'g':
index=6;
case 'h':
index=7;
case 'i':
index=8;
case 'j':
index=9;
case 'k':
index=10;
case 'l':
index=11;
case 'm':
index=12;
case 'n':
index=13;
case 'o':
index=14;
}
return index;
}
public static void main(String[] args) {
String myStr = "7h";
char c =myStr.charAt(1);
System.out.println("the char at position 1 is "+c);
Check check = new Check();
int result = check.columnToInt(c);
System.out.println(result);
}
}
Java switch statements can be a bit annoying to use. You need to use break or all the cases after the expected one will be executed as well.
switch(c) {
case 'a':
index=0;
break;
Alternatively you can use a return.
switch(c) {
case 'a':
return 0;
You must add the break keyword for each case.
For example:
case 'a':
index=0;
break;
otherwise next assignments are applied.

How to write a switch statement, specifically a default statement

I'm a beginner learning Java, and my teacher gave me this question:
Write a switch statement which assigns a value to char grade based on
the value of int variable score.
A score between 0 and 4 inclusive gets an 'F'.
A score of 5 or 6 gets a 'D'
A score of 7 gets a 'C'
A score of 8 gets a 'B'
A score of 9 or 10 gets an 'A'
Any other score gets an 'X'.
No other code than the switch statement itself should be included.
Here's what I wrote:
switch (grade) {
case 'A':
break;
case 'B':
break;
case 'C':
break;
case 'D':
break;
case 'F':
break;
case 'X':
break;
}
After running it on the website, I found that all cases worked except 'X'. So I tried:
default: grade = 'X'
But that also did not work.
How can I add 'X' as a default for this switch statement, and what can help me prevent myself from making this mistake again?
The switch may be used the other way, score > grade and not grade > ... as you did
static char scoreToGrade(int score) {
switch (score) {
case 0:
case 1:
case 2:
case 3:
case 4:
return 'F';
case 5:
case 6:
return 'D';
case 7:
return 'C';
case 8:
return 'B';
case 9:
case 10:
return 'A';
default:
return 'X';
}
}
Or with the other switch expression
static char scoreToGrade(int score) {
return switch (score) {
case 0, 1, 2, 3, 4 -> 'F';
case 5, 6 -> 'D';
case 7 -> 'C';
case 8 -> 'B';
case 9, 10 -> 'A';
default -> 'X';
};
}
Then call
char grade = scoreToGrade(4);
char grade = scoreToGrade(8);
Welcome to StackOverflow. Reading the requirement, you should rethink what is the purpose of the question. The switch statement shouldn't use the grade as a parameter, but the score. Before executing the function, you only know the score: the input is the score, and the output of your function is the grade. Using the score in the case conditions and return from there the grades. As the code executes sequentially, the last statement should be default, returning the X.
Lets try to explain this as easy as possible.
You want to check the score to assign a grade.
Switch takes a variable, in your case you placed grade, and checks if it matches with the cases, in case the grade is equal to A, to B,C...
If I explained it well, the first problem should be easy to see, you are checking the variable your are trying to assign.
You don't have a value for grade at the start, so its imposible to check a condition.
So you should check score (placing it on the switch), and assign grade inside the cases.
String grade; //no values
int score=4; //The variable we want to check
switch (score) {
case 0:
grade = "F";
break;
case 1:
grade = "F";
break;
case 2:
grade = "F";
break;
case 3:
grade = "F";
break;
case 4:
grade = "F";
break;
case 5:
grade = "D";
break;
case 6:
grade = "D";
break;
case 7:
grade = "C";
break;
case 8:
grade = "B";
break;
case 9:
case 10:
grade = "A";
break;
default:
grade = "X";
}
You can imagine it like a series of if checking for equality:
if(score==0){
grade="F";
}
if(score == 1){
grade="F";
}
if(score == 2){
grade="F";
}
if(score == 3){
grade="F";
}
if(score == 4){
grade="F";
}
if(score == 5){
grade="D";
}
if(score == 6){
grade="D";
}
//and so on
(It would more precise to use else if, but this is an example trying to make it as easy as possible, also doesn't cover all switch functionality, but you can get an idea of what I mean with checking and assigning).
At the end, your grade variable will have a value, cause you assigned it in the switch cases.
You can improve that switch, getting rid of the breaks on the firs 4 cases, so it will work like a "cascade", jumping to the next case until it finds a break:
String grade; //no values
int score=4 //The variable we want to check
switch (score) {
case 0:
case 1:
case 2:
case 3:
case 4:
grade = "F";
break;
case 5:
grade = "D";
break;
case 6:
grade = "D";
break;
case 7:
grade = "C";
break;
case 8:
grade = "B";
break;
case 9:
case 10:
grade = "A";
break;
default:
grade = "X";
}

Adding non-Latin number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to manipulate my mother language mathematical number in Java.
Example:
int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
I want to add and show these number in my language. As in the following:
int a = ၁;
int b = ၂;
int c = a + b;
System.out.println(c);
supposed that 'a' through 'j' represent 0 to 9 in your mother language and numbers are written left to right.
it's better if you convert the input and output to normal integers and work with them. because this way you have access to all Mathematical methods that java provides and more important java's libraries are more robust than your own methods.
this two method will convert String object(your wanted characters to int)
to int and Vice versa.
public static String convertToString (int value){
StringBuilder result = new StringBuilder();
for (int i=1;value/i>0;i *= 10)
switch( value % (i*10) / i){
case 0:
result.append('a');
break;
case 1:
result.append('b');
break;
case 2:
result.append('c');
break;
case 3:
result.append('d');
break;
case 4:
result.append('e');
break;
case 5:
result.append('f');
break;
case 6:
result.append('g');
break;
case 7:
result.append('h');
break;
case 8:
result.append('i');
break;
case 9:
result.append('j');
break;
}
return result.reverse().toString();
}
public static int convertToInt(String string){
int result = 0;
int j =1;
for (int i=string.length()-1;i>=0;i--,j *= 10)
switch(string.charAt(i)){
case 'b':
result += 1*j;
break;
case 'c':
result += 2*j;
break;
case 'd':
result += 3*j;
break;
case 'e':
result += 4*j;
break;
case 'f':
result += 5*j;
break;
case 'g':
result += 6*j;
break;
case 'h':
result += 7*j;
break;
case 'i':
result += 8*j;
break;
case 'j':
result += 9*j;
break;
}
return result;
}

How to use switch in array comparison? [duplicate]

This question already has answers here:
Using switch statement with a range of value in each case?
(20 answers)
Closed 7 years ago.
I want to compare array length with some int values. I can do it with if else but how to do it with switch because switch is fast and I want to use that in my project
switch (array.length) {
case array.length <= 11: // how to do this
break;
default:
break;
}
With if else I can do this:
if (array.length <= 5) {
//my is code here
}
else if (array.length <= 15) {
//my is code here
}
else if (array.length <= 10) {
//my is code here
}
You can't. switch can only test exact values.
You could do:
switch(array.length) {
case 0: case 1: case 2: case 3:
case 4: case 5: case 6: case 7:
case 8: case 9: case 10: case 11:
// do stuff
break;
default:
break;
}
But why do you want to do this? What makes you think it's faster?
switch is not the same as if (...) { ... } else { ... }. You can only use == within a case. You would have to do something like this:
int length = array.length;
switch (length) {
case 0:
case 1:
case 2:
[...]
case 11:
// your code here
break;
//other cases here
}
Notice the missing break-statements, they are quite important.
I would recommend this tutorial for more details.
You can't do it(as per your example) using switch. Since the values of case are constant expression (case *value*).
Switch statements operate by exact matches rather than comparisons like if does. You can do what you want by introducing a new variable like this:
int value = (array.length <= 11 ? 0 : (array.length <= 20 ? 1 : 2));
switch (value) {
case 0: // 11 or under
break;
case 1: // 12 to 20
break;
case 2: // 21 or more
break;
}
I don't know if this buys you much over if/else statements, but if you find it cleaner to code, you can do it.
In your if/elseif, the if(array.length<=10) will never run because if(array.length<=15) is checked above it.
Doing this with an if/elseif structure would require less lines of code.
If you want to do this using a switch/case statement, this would work:
int length = array.length;
switch(length) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5: {
System.out.println("Case 0<=length<=5 triggered.");
break;
}
case 6:
case 7:
case 8:
case 9:
case 10: {
System.out.println("Case 6<=length<=10 triggered.");
break;
}
case 11:
case 12:
case 13:
case 14:
case 15: {
System.out.println("Case 10<=length<=15 triggered.");
break;
}
default: {
System.out.println("Default case triggered.");
}
}

Switch Statement Inside a method of another class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public int alphCheck(char check){
switch(check){
case 'a':
return 1;
break;
case 'b':
return 2;
break;
case 'c':
return 3;
break;
case 'd':
return 4;
break;
case 'e':
return 5;
break;
case 'f':
return 6;
break;
case 'g':
return 7;
break;
case 'h':
return 8;
break;
case 'i':
return 9;
break;
case 'j':
return 10;
break;
case 'k':
return 11;
break;
case 'l':
return 12;
break;
case 'm':
return 13;
break;
case 'n':
return 14;
break;
case 'o':
return 15;
break;
case 'p':
return 16;
break;
case 'q':
return 17;
break;
case 'r':
return 18;
break;
case 's':
return 19;
break;
case 't':
return 20;
break;
case 'u':
return 21;
break;
case 'v':
return 22;
break;
case 'w':
return 23;
break;
case 'x':
return 24;
break;
case 'y':
return 25;
break;
case 'z':
return 26;
break;
}
}
PS.This was done in another class
I want to be able to use this method in the main class, to input a letter, and return a number/index for that letter.
But I kept getting: this method must return a result of type int.
Very Confused. Please help. Thx.
Here's a question to consider: What happens if the inputted letter isn't one of the cases you described?
While you may know that you're only feeding in letters, the compiler doesn't know that, and because it can't figure out what to return if one of the cases you defined isn't hit, emits an error as a result. You'll need to put in a default case, so the compiler knows that the method is guaranteed to return something:
switch(check) {
case 'a':
...
default:
// return something or maybe print/throw an error
}
A better solution for this may be to use the fact that chars are just numbers in a different form. For example, 'a' is equivalent to the integer 97 (check out the table here for a table of characters and their ASCII numerical equivalents). So you can do a math trick to get equivalent results:
public int alphCheck(char check) {
return check - 'a' + 1;
}
you have to provide return type like return 0; at the end of your switch statement.or in default: case
switch(check) {
..
default:
return 0;
}

Categories