Switch statement Test learners

We need your help to improve an adaptive system. There's a program that asks learners what programming language they are learning. There are four options, one of them is correct:

  1. Java
  2. Kotlin
  3. Scala
  4. Python

Your task: read the answer’s number from the standard input and output the result of the test: "Yes!", "No!" or "Unknown number". We hope you know, which answer is correct. You don't need to print the question itself.

Sample Input 1:

1

Sample Output 1:

Yes!

Sample Input 2:

6

Sample Output 2:

Unknown number

Solution:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        switch (new Scanner(System.in).nextLine()) {
            case "1":
                System.out.println("Yes!");
                break;
            case "2":
            case "3":
            case "4":
                System.out.println("No!");
                break;
            default:
                System.out.println("Unknown number");
        }
    }
}

若几个case语句指向相同的结果,可以利用case语句没有break按顺序执行的特性,省略前几个case语句后的内容,只需在最后一个case语句补充结果。

posted @ 2020-08-11 14:34  longlong6296  阅读(131)  评论(0)    收藏  举报