Converting if-else to switch case statement [duplicate]

134
July 02, 2019, at 06:20 AM

This question already has an answer here:

  • In Java,Using switch statement with a range of value in each case? 17 answers
  • How to use greater than or equal in a switch statement 8 answers

I've recently started learning Java. My teacher has given us this homework assignment which is about writing and converting the If-Else statement code below into a Switch-Case statement code. I wrote the If-Else statement code correctly but the Switch-Case one seems to have a few errors. The sooner I can get an answer the better. Thanks.

What I want converted:

int x;
System.out.println("type in a mark to see what grade it is");
Scanner input = new Scanner(System.in);
x = input.nextInt();
if (x >= 90 && x <= 100) {
    System.out.println("A");
}
if (x >= 80 && x < 90) {
    System.out.println("B");
}
if (x >= 70 && x < 80) {
    System.out.println("C");
}
if (x >= 60 && x < 70) {
    System.out.println("D");
}
if (x >= 50 && x < 60) {
    System.out.println("E");
}
if (x < 50 && x > 0) {
    System.out.println("F");
}
if (x <= 0 || x > 100) {
    System.out.println("invalid mark");
}

What I tried:


Scanner input = new Scanner(System.in);
int x = input.nextInt();
switch (x) {
    case x >= 90 && x <= 100:
        System.out.println("A");
            break;
    case x >= 80 && x < 90:
        System.out.println("B");
            break;
    case x >= 70 && x < 80:
        System.out.println("C");
            break;
    case x >= 60 && x < 70:
        System.out.println("D");
            break;
    case x >= 50 && x < 60:
        System.out.println("E");
            break;
    case x < 50 && x > 0:
        System.out.println("F");
            break;
    default:
        System.out.println("invalid mark");

Doesn't give any actual output besides a few syntax error messages.

Answer 1

Since your switch statement has int variable x as an input parameter, all case statements have to check int value, not boolean. That's why you get incompatible types error. You can do:

switch (x / 10) {
    case 9:
        System.out.println("A");
        break;
    case 8:
        System.out.println("B");
        break;
    ...

See more java doc switch statement

Answer 2

Not sure if this is what your teacher is looking for, but I'd do this with an enum.

enum Grade {
    A(90, 100),
    B(80, 90),
    C(70, 80),
    D(60, 70),
    E(50, 60),
    F(0, 50);
    private Grade(int from, int to) {
        fromScore = from; toScore = to;
    }
    private int fromScore, toScore;
    boolean inRange(int score) {
        return score >= fromScore && score < toScore);
    }
    public static Grade fromScore(int score) {
        for (Grade gr : Grade.values()) {
            if (gr.inRange(score)) { return gr; }
        }
        throw new InvalidGradeException(score); // TODO
    }
}

You can then do

Scanner input = new Scanner(System.in);
x = input.nextInt();
try {
    Grade gr = Grade.fromScore(x);
    switch (gr) {
        case A: System.out.println("grade is A"); break;
        case B: System.out.println("grade is B"); break;
        case C: System.out.println("grade is C"); break;
        case D: System.out.println("grade is D"); break;
        case E: System.out.println("grade is E"); break;
        case F: System.out.println("grade is F"); break;
    }
} catch (InvalidGradeException ex) {
    System.out.println("invalid score");
}

In fact, the switch becomes pointless because you can just do

System.out.printf("Grade is %s%n", Grade.fromScore(x).name());
Answer 3

The casein a switch needs a constant. See http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 for the exact definition of what a constant expression is.

You may 'optimize' your if a little bit with elses ...

        Scanner input = new Scanner(System.in);
        int x = input.nextInt();
        if (x >= 90 && x <= 100) {
            System.out.println("A");
        } else if (x >= 80 && x < 90) {
            System.out.println("B");
        } else if (x >= 70 && x < 80) {
            System.out.println("C");
        } else if (x >= 60 && x < 70) {
            System.out.println("D");
        } else if (x >= 50 && x < 60) {
            System.out.println("E");
        } else if (x < 50 && x > 0) {
            System.out.println("F");
        } else if (x <= 0 || x > 100) {
            System.out.println("invalid mark");
        }

By the way, I think I would rewrite the computation of the grade the following way :

private static char computeMark(int x) {
    if (x <= 0 || x > 100) {
        throw new IllegalArgumentException("Invalid mark : " + x);
    }
    return (char) ((int)'A' + ((99-Math.max(49, x))/10));
}

HTH!

READ ALSO
@RefreshScope in Configuration class

@RefreshScope in Configuration class

I have a spring boot applicationI am using Spring Cloud Config to externalize properties - through Git

202
implement 2 different listeners at the same class and adding at a swing component

implement 2 different listeners at the same class and adding at a swing component

I would like to add 2 listeners at my JList: MouseListener and KeyListener; and use only MouseClicked et Keypressed but at the same class

79
Add a bias to a score using a graph function

Add a bias to a score using a graph function

I am trying to update a calculator written in Java that places data in an order according to several criteriaThe ordering is arrived at by a scoring system

110
Java MS Graph SDK Post Message with attachment

Java MS Graph SDK Post Message with attachment

I'm trying to send a message with attachment through Microsoft Graph Sdk for Java

217