简体   繁体   English

为什么我的程序无法识别输入“ q”并中断循环?

[英]Why doesn't my program recognize the input “q” and break the loop?

I'm writing a main method that asks the user for input in the form of the length of the radius and height of a cone, and then calls 3 other mathematical methods to determine the area of the bottom of the cone, as well as the surface area and volume of it. 我正在编写一种主要方法,要求用户以圆锥体的半径和高度的长度形式输入,然后调用其他3种数学方法来确定圆锥体底部的面积以及表面积和体积。

The idea is that you should be able to enter several sets of inputs, and signal that you're done by entering "q". 这个想法是,您应该能够输入多组输入,并通过输入“ q”来表示已完成操作。 An example input could for example be " 10 5 6 8 q". 输入示例例如可以是“ 10 5 6 8 q”。 The program should then calculate everything two times, with two sets of radius and height and then break the loop. 然后,程序应使用两组半径和高度两次计算所有内容,然后中断循环。 Instead, it does the calculations 3 times, where the last two are identical. 取而代之的是,它将进行3次计算,其中最后两个是相同的。 Also it doesn't jump to the next piece of code after the infinite loop. 同样,它不会跳到无限循环之后的下一段代码。

outerLoop: while(true)       //Infinite loop
{   
if (scan.hasNextInt())       //If next input is an integer, read it
{
radie = scan.nextInt();
height = scan.nextInt();
}
else if (scan.next().equals('q'))
{                          //If it instead if "q", break the loop  
    break outerLoop;
}
     System.out.print("r = "+radius);
     System.out.println("h = "+height);
     System.out.println("Bottom area:      "+ area(radius));
     System.out.println("Surface area:   "+area(radie, height));
     System.out.println("Volume:              "+ volume(radius, height));

}

}

您正在将一个字符串(scan.next())与一个字符'q'比较,该字符将永远不相等。

else if (scan.next().equals("q"))
{                          
    break outerLoop;
}

You are comparing a String vs a Char. 您正在比较字符串与字符。 Try with this and it will work. 试试这个,它将起作用。

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

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