如何在Java中使用“ 0”停止do while循环

时间:2018-10-29 20:05:10

标签: java

我只想首先说我是一个初学者,所以我对我的(确实)糟糕的代码表示歉意。

我正在创建一个程序,您在其中输入int并使用do while循环打印出平方根。当您输入“ 0”时,程序将停止。

如何阻止它?

public static void main(String[] args)
{

    Scanner InputNum = new Scanner(System.in);

    DecimalFormat formatTenths = new DecimalFormat("0.0");

    do {
        System.out.println("Please enter an integer.");
        int sqroot = InputNum.nextInt();
        double Finalsqroot = Math.sqrt(sqroot);
        System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
    } while (sqroot==0);
    System.out.println("Closing...");


    InputNum.close();

}

}

3 个答案:

答案 0 :(得分:2)

您需要测试输入的值是否为0(我将测试小于或等于零,因为负数的平方根是虚数)。如果是这样,请break循环。喜欢,

int sqroot = InputNum.nextInt();
if (sqroot <= 0) {
    break;
}

答案 1 :(得分:0)

尝试

public static void main(String[] args) {

    Scanner InputNum = new Scanner(System.in);

    DecimalFormat formatTenths = new DecimalFormat("0.0");
    int sqroot = 0;
    do {
        System.out.println("Please enter an integer.");
        sqroot = InputNum.nextInt();
        double Finalsqroot = Math.sqrt(sqroot);
        System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
    } while (sqroot != 0);
    System.out.println("Closing...");

    InputNum.close();
}

我只是在您的while之外初始化sqroot,然后将==更改为!=

答案 2 :(得分:-1)

此学术练习可能要求使用do / while循环,但是如果您不受限制地使用它,则for循环也可以使用:

public static void main(String[] args)
{

    Scanner InputNum = new Scanner(System.in);

    DecimalFormat formatTenths = new DecimalFormat("0.0");

    System.out.println("Please enter an integer.");
    for(int sqroot = InputNum.nextInt(); sqroot > 0; sqroot = InputNum.nextInt()) {
        double Finalsqroot = Math.sqrt(sqroot);
        System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
    }
    System.out.println("Closing...");


    InputNum.close();

}

问题中提出的程序有一个固有的缺陷:您要求输入,然后立即尝试对其进行处理(计算平方根),而不确定是否适合使用。

切换到for循环是可以克服的一种方法,因为它鼓励程序流程“询问输入”,“检查输入是否可接受”,“使用输入”,“重复”

如果您被迫使用do / while循环,那么您仍然需要遵循此流程,Elliott Frish在他的回答中着眼于此,建议您将“检查输入是否可接受”部分添加为双重目的测试输入是否为<=0。这样的值对于平方根运算是不可接受的,并且您还希望在遇到它们时结束程序,因此该测试可用于实现两个目标

侧边琐事,for循环几乎可以排他地使用:

for(;;) //same as while(true)
for(;test;) //same as while(test)
for(bool do = true; do; do = test) //same as do..while(test)

..尽管对于同一作业,使用whiledo可能比使用for循环更具可读性

请注意,您的while(sqroot==0)是一个错误。您不想在用户输入0时继续循环,而您不想输入0时继续循环...

相关问题