簡體   English   中英

如何比較 Java 中 switch 語句中的 int 變量?

[英]How to compare int variables in switch-statements in Java?

在 if 語句中,您可以僅使用模數來檢查某些內容是否可整除,例如“if (number % 3 == 0);”。

當嘗試在 switch 語句中執行與“case (number % 3 == 0):”相同的操作時,它表示需要:int,provided:boolean。 我該如何解決這個問題? 還有一個簡短的解釋為什么你會像你說的那樣做,將不勝感激!

做一個基本的練習,看看輸入的數字是否能被 3、5、兩者或兩者都整除。 做 if 語句很容易,但這個不一樣。

當前代碼是(如果形式相同,因為我不知道該怎么做)。 問題加粗:

public static void main(String[] args) {
    Scanner numberEntered = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = numberEntered.nextInt();


    switch (number) {

        case **(number  % 3 == 0)**:
            System.out.println("Fizz");
            break;

試圖解析為布爾值和一些奇怪的隨機事物,但我沒有嘗試想出對我有用的東西。

嘗試這個

public static void main(String[] args) {
    Scanner numberEntered = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = numberEntered.nextInt();

    switch (number  % 3) {

        case (0):
            System.out.println("Fizz");
            break;

像這樣嘗試:

    switch (number % 3) {

    case (0):
        System.out.println("Fizz");
        break;
    }

正如Mark Rotteveel已經評論過的那樣,可能無法通過 Java 中的 Switch 做到這一點。 我建議您在這里使用嵌套的 IF 語句。 就像這樣:

public static void main(String[] args) {
    Scanner numberEntered = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = numberEntered.nextInt();

    if((number%3==0) && (number%5==0)) {
        System.out.println("entered number is divisible with both 3 and 5!")
    } 
    else if (number%3==0) {
        System.out.println("entered number is divisible with 3!")
    }
    else if (number%5==0) {
        System.out.println("entered number is divisible with 5!")
    }
    else if (!(number%3==0) && !(number%5==0)) {
        System.out.println("entered number is NOT divisible with 3 or 5!")
    }
}

希望這會有所幫助。

像這樣簡單的使用

public static void main(String[] args) {

    Scanner numberEntered = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int number = numberEntered.nextInt();

    switch (number % 3 ) {
        case (0):
            System.out.println("Do something");
            break;
        default:
            break;
    }
}

如果您正在做 FizzBu​​zz 練習,我建議您使用三元運算符。

        Scanner input = new Scanner(System.in);
        while (true) {
            int n = input.nextInt();
            if (n <= 0) {
                break;
            }
            String v = n % 15 == 0 ? "FizzBuzz"
                    : n % 3 == 0 ? "Fizz"
                            : n % 5 == 0 ? "Buzz"
                                    : "Not divisible by 3 or 5";
            System.out.println(v);

        }

它的工作原理如下:

int ret = boolean expression ? a : b.

如果表達式為真,返回a,否則返回b。 a 和 b 也可以是三元表達式,因此可以鏈接起來。

在上面的代碼中。

  • 如果它可以被 15 整除,那么 FizzBu​​zz
  • 否則如果是 3,Fizz
  • 否則如果到 5,嗡嗡聲
  • 否則不能被兩者整除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM