switch语句语法错误
我正在尝试测试我的用户是否提交了合理的数据,该数据稍后被格式化为整数。 switch语句的问题出在哪里? :)
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
I am trying to test if my user submits sensible data , which is later formatted to integer.
Where is the problem with the switch statement? :)
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在切换 x,它是一个字符串 - 除非您使用 Java 7,否则不能在 Switch 语句中使用字符串。
我预计错误实际上来自 str.startsWith(),该方法期望获取一个字符串(您正在检查它的开头)并返回一个布尔值,您可以'也不要打开。
更新更正您的代码以执行我认为您想要执行的操作:
尽管较短的方法只是执行 Integer.parseInt 调用,并处理可能会出现的 NumberFormatException发生 - 那么你根本不需要进行切换。
您需要return i;并将方法签名从void转换为int,或者以其他方式公开i中的数据使其变得值得。
You're switching on x which is a String - unless you're using Java 7, you can't use String in a Switch statement.
I expect the error is actually coming from str.startsWith(), where that method is expecting to take a String (which you're checking what it starts with) and returns a boolean, which you can't switch on either.
UPDATE Correcting your code to do what I think you're trying to do:
Although the shorter way is just to do the Integer.parseInt call, and handling the NumberFormatException that may occur - then you don't need to do the switch at all.
You need to either return i; and convert the method signature from void to int, or otherwise expose the data in i to make it worthwhile.
x 是一个字符串,以防您测试数字。
尝试:
x is a string and in case you test number.
try:
如果您尝试测试输入的字符串是否为整数,那么我认为没有理由首先使用 switch() 。在尝试使用该函数时捕获引发的异常会是更好的行为。
例子:
If you're trying to test to see if the string entered is an Integer, then I see no reason to have the
switch()
in the first place. It would be far better behavior to catch the exception raised when trying to work with the function.Example:
您的
x
是一个字符串。 switch 语句尝试将其与整数值进行比较。你需要这样的东西:编辑:实际上,现在我看到该字符串应该是startsWith调用的结果,我对这段代码想要做什么完全感到困惑。
Your
x
is a String. The switch statement is attempting to compare it against integer values. You need something like this:EDIT: Actually, now that I see that the string is supposed to be the result of a startsWith call, I'm totally confused about what this code is trying to do.