Hi guys, Im having trouble with my switch statement..
i have this so far:
import javax.swing.*;
public class Lab4Switch {
public static void main ( String[] args){ String mark_string;
mark_string = JOptionPane.showInputDialog(null, "Enter your mark: ");
int mark = Integer.parseInt(mark_string);
switch(mark){
case (mark < 84):JOptionPane.showInputDialog(null, "Grade is HD"); break; case (mark < 74): JOptionPane.showMessageDialog(null, "Grade is D"); break; case (mark < 64): JOptionPane.showMessageDialog(null, "Grade is P"); break; case (mark < 54): JOptionPane.showMessageDialog(null, "Grade is F"); break; default: System.exit(0); } }
Im not sure how to make it work... i think there is something wrong with my expression..
Switch only accepts constants, not conditions. It can only check if values are equal, not if one is bigger or smaller than another.
switch (n) {
case 1:
break;
case 2:
break;
default:
}
In your case you have to use
if (mark < 84) {
} elseif(mark < 74)) {
} elseif(mark < 64)) {
} else {//error case, mark is >= 84
}
You can write it also like this:
String grade = "Grade is " + mark < 84 ? "HD"
: mark < 74 ? "D"
: mark < 64 ? "P"
: mark < 54 ? "F"
: "INVALID"; //case mark >= 85
This is a if-then-else statement which allows only one assignment. a = (condition) ? value1 : value2; I just replaced value2 with another statement. Sometimes you have to add brackets for the compiler to understand it. In this case it should work just fine.