Java 中的孤立大小写错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32587568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Orphaned Case Error in Java
提问by Aryan Srivastava
Im a beginner in the coding world. I have been learning Java recently when i came across a speedbump.
我是编码世界的初学者。我最近在学习 Java 时遇到了一个障碍。
First of all heres the code :
首先是代码:
import java.util.*;
public class Stuff {
public static void main(String []args); {
Scanner identity = new Scanner(System.in);
String id;
System.out.println("Please Enter Your Name :");
id = identity.next();
Switch (id); {
case "name1":
//some code here....
break;
case "name2":
//some code here....
break;
case "name3":
//some code here....
break;
case "name4":
//some code here....
break;
default :
//some code here....
break;
}
}
}
The error
错误
Error: Orphaned case
case: "name1";
I cant seem to find why this is happening and have googles to no avail.
我似乎无法找到为什么会发生这种情况并且谷歌无济于事。
Edit : Some people have said that I am ending Switch early with the semi colon. But when i add it, i get a new error along with the previous one:
编辑:有些人说我会用分号提前结束 Switch。但是当我添加它时,除了上一个错误之外,我还会收到一个新错误:
Error: ';' expected
Switch (id) {
^
采纳答案by Suresh Atta
You ran into multiple problems here.
您在这里遇到了多个问题。
Problem 1 :
问题1:
Switch (id); {
----------^
Look carefully your ;
ends your switch
there right away.
仔细看看你的;
结局switch
马上就到了。
Apparently all your case
statements became orphans :)
显然你所有的case
陈述都变成了孤儿:)
Problem 2 :
问题2:
Your Switch
should be switch
(lower case s)
你Switch
应该是switch
(小写s)
Problem 3 :
问题 3:
One more ;
cause you compile time error at the line
另一个;
原因是您在该行编译时出错
public static void main(String []args); {
-----^
Note: I strongly suggest you to use an IDE, to save lot of time here. It tells you the compiler errors on the fly.
注意:我强烈建议您使用 IDE,以节省大量时间。它会即时告诉您编译器错误。
回答by James Wierzba
Your syntax for the switch statement is wrong.
您的 switch 语句语法错误。
switch (id) {
case "name1":
//some code here....
break;
case "name2":
//some code here....
break;
case "name3":
//some code here....
break;
case "name4":
//some code here....
break;
default :
//some code here....
break;
}
回答by Kumar Abhinav
The semicolon after the Switch (id);
statement effectively terminates the switch case and the cases you define afterwards are orphan(i.e. without any switch case)
语句后面的分号Switch (id);
有效地终止了 switch case,之后你定义的 case 是孤立的(即没有任何 switch case)
回答by Marged
What you try will need a quite current version of Java because you use String
s with switch
.
您尝试的操作将需要最新版本的 Java,因为您将String
s 与switch
.
And you have to
你必须
switch (id)
So please remove the ;
所以请删除 ;
回答by Thomas Jungblut
You are finishing the switch statement early:
您正在提前完成 switch 语句:
Switch (id); {
The real syntax is:
真正的语法是:
switch (id) {
// your cases
}