【问题标题】:How to avoid error in default condition in the switch statement in the new way JavaJava新方式如何避免switch语句中默认条件出错
【发布时间】:2020-10-07 17:10:23
【问题描述】:

如何避免“default”中的switch语句出错?这个switch case是根据新标准编写的。

import java.util.Scanner;
public class SwitchCase {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Choose option: ");
        char userChoice = scan.next().charAt(0);
        switch (userChoice) {
            case '1' -> System.out.println("1 funkcja");
            case '2' -> System.out.println("2 funkcja");
            default ->
                if((!Character.isDigit(userChoice))||(userChoice>3)){     #this part throws an error below:
                  System.out.println("Input error");
            }
        }
        scan.close();
    }
}

一个错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error, insert "ThrowExpression ;" to complete SwitchLabeledThrowStatement
    Syntax error, insert "}" to complete SwitchBlock
    Syntax error on token "}", delete this token

    at SwitchCase.main(SwitchCase.java:11)

【问题讨论】:

  • default -> { /* if statement */ }

标签: java switch-statement


【解决方案1】:

检查这个: 您需要将 : 用于切换案例。 我们正在将 char 的 userChoice 与 3(an int) 进行比较。

  public static void main(String[] args) {
       
    Scanner scan = new Scanner(System.in);
    System.out.print("Choose option: ");
    char userChoice = scan.next().charAt(0);
    switch (userChoice) {
        case '1': System.out.println("1 funkcja");
        case '2': System.out.println("2 funkcja");
        default:
            if(!Character.isDigit(userChoice)||(Integer.parseInt(String.valueOf(userChoice))>3)){     //#this part throws an error below:
              System.out.println(userChoice + " Input error");
        }
    }
    scan.close();
       
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多