为什么我的中断不能在我的java循环中工作

时间:2014-02-24 20:14:33

标签: java

    String prompt;
    boolean promptB;

    runLoop:

    do{
        Scanner input = new Scanner (System.in);
        System.out.println("Enter a number, a space and F to convert from degF to degC and C to convert to degC to degF");

        if(input.hasNextDouble()){
            double deg = input.nextDouble();
            String letter = input.next().toUpperCase();
            char dg = letter.charAt(0);

            tempLoop:

            if( dg == 'C' || dg == 'c'){

                double cTemp= (double)(deg-32)*(5.0/9.0);
                System.out.printf("%f degC converted to degF is %.2f%n ", deg, cTemp );
            }
            else if(dg == 'F' || dg == 'f'){
                double fTemp = (double) (deg*9/5) + 32;
                System.out.printf("%f degF converted to degC is %.2f%n ", deg, fTemp );
            }
            else{
                System.out.println("That character does not correspond to a valid unit of measure ");
                break tempLoop;
            }
            do{
                System.out.println("Would you like to continue?(yes/no)");
                prompt = input.next().toLowerCase();

                if(prompt.equals("yes")){
                    promptB = false;

                } else if (prompt.equals("no")){
                    promptB = false;
                    break;

                }else{
                    promptB = true;
                    System.out.println("Would you like to continue? yes or no");
                    prompt = input.next();
                }

            }while(promptB);
        }
        else{
            System.out.println("must enter in a valid number for degrees");
            break runLoop;
        }
    }while(prompt.equalsIgnoreCase("yes"));

}

}

这是我目前的代码。我无法弄清楚如何重新执行runLoop:如果input.hasNextDouble()不为true或用户输入字母而不是double。非常欢迎任何信息的想法

2 个答案:

答案 0 :(得分:1)

要使其有效,只需将break runLoop更改为continue runLoop即可。您还需要初始化prompt变量,例如String prompt = "yes";

但是你应该真的重构这段代码,因为它看起来很容易出错。

答案 1 :(得分:0)

简化此代码的一种方法是将代码放在一个单独的方法中,并在main方法中调用该方法。例如:

public static void main(String[] args) throws FileNotFoundException {
    runLoop();
}

当有人没有输入双人时:

System.out.println("That character does not correspond to a valid unit of measure ");
runLoop(); //this will restart the method

System.out.println("Would you like to continue?(yes/no)");
prompt = input.next().toLowerCase();
if (prompt.equals("yes")) {
      runLoop();

} else if (prompt.equals("no")) {
       System.exit(1);