英文:
How to avoid error in default condition in the switch statement in the new way Java
问题
以下是已翻译的代码部分:
如何避免在“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("选择选项:");
char userChoice = scan.next().charAt(0);
switch (userChoice) {
case '1' -> System.out.println("1 函数");
case '2' -> System.out.println("2 函数");
default ->
if ((!Character.isDigit(userChoice)) || (userChoice > 3)) { // 此部分会引发下面的错误:
System.out.println("输入错误");
}
}
scan.close();
}
}
一个错误:
Exception in thread "main" java.lang.Error: 未解析的编译问题:
语法错误,插入“ThrowExpression ;”以完成 SwitchLabeledThrowStatement
语法错误,插入“}”以完成 SwitchBlock
在标记“}”上的语法错误,删除此标记
at SwitchCase.main(SwitchCase.java:11)
英文:
How do I avoid an error in switch statement in "default"?This switch case is wiritten according to the new standrads.
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();
}
}
An error:
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)
答案1
得分: 1
这样检查:
你需要使用冒号(:)来分隔不同的switch case。
我们正在比较的是userChoice,它是一个字符,和3(一个整数)。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("选择选项:");
char userChoice = scan.next().charAt(0);
switch (userChoice) {
case '1': System.out.println("1 函数");
case '2': System.out.println("2 函数");
default:
if (!Character.isDigit(userChoice) || (Integer.parseInt(String.valueOf(userChoice)) > 3)) {
System.out.println(userChoice + " 输入错误");
}
}
scan.close();
}
英文:
Check this:
You need to use : for switch cases.
We are comparing userChoice which is char to 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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论