【发布时间】:2017-04-01 14:47:15
【问题描述】:
我知道java中没有goto,但我问一般是否有从if到else的goto的方法
示例:
public void decToAsci(String decimal) {
String nb = "";
int number;
for (int i = 0; i < decimal.length(); i++) {
Character c = decimal.charAt(i);
if (!c.equals(' ')) {
nb += decimal.charAt(i);
if (i == decimal.length() - 1)
//here i want to jump to else
// i can do it like this :
// System.out.print( (char) Integer.parseInt(nb) + " ");
// but i repeat code in else here ..i just want to jump to else
} else {
number = Integer.parseInt(nb);
System.out.print((char) number + " ");
nb = "";
number = 0;
}
}
}
我试试这个:
if (!c.equals(' ')) {
nb += decimal.charAt(i);
if (i == decimal.length() - 1) continue label;
} else {
label: the code in else
}
但没有工作,也没有使用中断标签。我明白继续,休息。像这样在儿子和父母之间使用吗? :
label:
for(int i=0 ; i<n ; i++)
if (cond) break label;
我问一个可以从if跳转到else的方法(2个儿子)
(不是儿子和父母,而是在两个儿子之间跳跃)
我认为即使在 c 和 c++ 4 示例中使用 goto,我们也做不到
【问题讨论】:
-
使用方法。从 if 块和 else 块中调用相同的方法。这就是避免代码重复的方法。您编写一个包含该代码的方法并从多个位置调用它。
-
这是唯一的解决方案吗?
-
将
if(i==decimal.length()-1) continue label;更改为if(i!=decimal.length()-1) {/*do what you need*/}; -
没用,我想你不明白我的问题。无论如何谢谢..
-
@FakhRi 如果您想编写可维护、可读的代码,那么是的,这是唯一的解决方案。如果你想写意大利面条、不可读和难以维护的代码,那么 goto 和 switch fallthrough 就是你需要的。
标签: java string break goto continue