繁体   English   中英

中断并继续在Java中不起作用

[英]break and continue doesn't work in Java

我制作了这个程序来反转一个字符串。 它可以通过两种方式完成。 所以我想问用户首选的方法。 为了摆脱if else我使用break关键字,后跟每个选择的标签。

该程序运行良好,没有中断和标签,但使用中断时却给我错误。

import java.util.Scanner;

public class ReverseString {

    public static void main(String[] args) {

        System.out.println("Choose a method:");
        Scanner ch = new Scanner(System.in);

        int choice = ch.nextInt();

        if (choice == 1)
        {
            break first;
        }
        else
        {
            break second;
        }

        first:

        Scanner in = new Scanner(System.in);

        System.out.print("Enter a string to reverse:");

        String original = in.nextLine();

        String reverse = "";
        int i, length = original.length();

        for (i=length-1; i>=0; i--)
        {
            reverse = reverse + original.charAt(i);
        }

        System.out.println(reverse);


        second:

        StringBuilder rev = new StringBuilder(in.nextLine());

        String revc = rev.reverse().toString();

        System.out.println(revc);


    }

}

和错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
    Syntax error, insert "AssignmentOperator Expression" to complete Assignment
    Syntax error, insert ";" to complete Statement
    Scanner cannot be resolved to a variable
    in cannot be resolved to a variable
    in cannot be resolved
    Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
    Syntax error, insert "AssignmentOperator Expression" to complete Assignment
    Syntax error, insert ";" to complete Statement
    StringBuilder cannot be resolved to a variable
    rev cannot be resolved to a variable
    in cannot be resolved
    rev cannot be resolved

    at welcome.ReverseString.main(ReverseString.java:25)

在Java中, break (和continue )主要用于循环,而breakswitch也起作用。 您可以使用break来突破带标签的块,但是坦白地说,使用if语句这样做没有多大意义。 JLS§14.15中的详细信息。)

与其尝试使用有效的“ goto”方法,不如将两个反转方法放入method中 ,然后从连接到ifelse (当前break )的块中调用适当的方法。

可以使用break in if语句,但必须标记这些块。 请参阅以下示例:

if (choice == 1) first: {
    // ...
    break first;
    // ...
} else second: {
    // ...
    break second;
    // ...
}

但是,您不能break方式使用它。

相反,我建议您按以下方式组织程序:

if (choice == 1) {
    // Code for choice 1
} else {
    // Code for choice 2
}

或者甚至更好的是,将代码拆分为较小的方法,然后执行

if (choice == 1) {
    method1();
} else {
    method2();
}

您使用break的方式是错误的,这是我看到的编译问题。 您正在if块中使用break break在循环中使用- whilefor跳过重命名迭代。

在这里,您可以将goto与标签一起使用。 但是,建议不要使用goto来组织程序流程。 更好的是,您可以更改程序流程。 顺便说一下,不要告诉break在java :)中不起作用,它已经被使用和测试了数千次。

希望对您有所帮助。
非常感谢

必须使用breakcontinue循环。

范例:

Outer:
       for(int i=0;i<5;i++)
       {

       }

这是完整的示例,详细信息以供参考

http://www.java-examples.com/java-break-statement-label-example

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM