【问题标题】:Syntax error on token goto throw expected [duplicate]令牌 goto throw 预期的语法错误 [重复]
【发布时间】:2013-01-12 20:09:43
【问题描述】:

可能重复:
Is there a goto statement in java?

在我的 android 应用程序中,我使用 goto 语句来控制流程。但我收到错误为“token goto 的语法错误,抛出预期”。这是我的代码

label:
if(alc)
{
  r_code=st.nextToken();
  AlertDialog.Builder alert=new AlertDialog.Builder(Fetch.this);
  alert.setTitle(count+" records found for "+rytname.getText().toString());
  alert.setMessage("Are you sure want to search for "+r_code+"?");
  alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
      ff=1;
      alc=false;
    }
  });

  alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {

   @Override
   public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      ff=0;
   }
  });
  alert.show();
  if (ff==0)
  {
    goto label;
}

我是这个 android 的新手,帮我避免这个错误

【问题讨论】:

  • 好的,但是如何避免这个错误呢?
  • Java 中没有 goto。它是一个保留字,但未被使用。
  • 仍在使用goto的人???

标签: android


【解决方案1】:

Java 中没有可用的goto

即使Java 关键字列表specifies the goto keyword,它也被标记为未使用。因此,它无法工作。您必须在不使用 goto 关键字的情况下重写您的代码。

一般提示:有Labeled Statements

语句可能有标签前缀。

LabeledStatement:
     Identifier : Statement

LabeledStatementNoShortIf:
     Identifier : StatementNoShortIf

标识符被声明为立即包含的语句的标签。

与 C 和 C++ 不同,Java 编程语言没有 goto 语句; 标识符语句标签与出现在带标签语句中的任何位置的break (§14.15)continue (§14.16) 语句一起使用。

标签语句的标签范围是立即 包含声明。 – JLS (§14.7)

但你真正想要的是重写你的构造而不使用它,例如使用while

while (f == 0) {
     // ...
}

【讨论】:

【解决方案2】:

代替:

label:
...// the rest of your code
if (ff == 0) 
{
    goto label;
}

使用这个:

do {
...// the rest of your code
while (ff == 0);

如果你能把它转换成:

while (ff == 0) {
...// the rest of your code
}

【讨论】:

    【解决方案3】:

    不建议在代码中使用goto,因为从可读性的角度来看会不清楚。可以使用breakcontinue 代替gotogoto 的替代品是 here

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 2022-01-12
      • 2012-08-02
      • 2021-05-03
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      相关资源
      最近更新 更多