0

我正在尝试编写一个程序,从用户那里读取 2 个数字并将它们分开。这是我到目前为止的代码:

import java.util.Scanner;

public class divideByZero {

public static int quotient(int numerator, int denominator)
{
   return numerator / denominator;
}

public static void main(String args[])
{
   Scanner scanner = new Scanner(System.in);

    System.out.print("Please enter the first number: ");

    int numerator = scanner.nextInt();

    System.out.print("Please enter the second number: ");

    int denominator = scanner.nextInt();

    int result = quotient( numerator, denominator );

    float result2 = (float)result;

    System.out.printf("\n The first number %d divided by the second number "
            + "%d = %f\n", numerator, denominator, result2 );

}

如何将其更改为 while 循环,使用 if 语句检查第二个数字,如果为 0,请用户输入不同的数字?

4

3 回答 3

4

这不是您问题的答案,但您需要将这些数字中的至少一个转换为双精度数。现在您将只进行整数除法,即 5/3 = 1。您可以使用 double num = (double) denominator 来执行此操作。

其次,这是对 do while 循环的一个很好的使用。继续询问数字,直到它不是 0。当您通过循环的第一次迭代没有条件时,您知道您想要一个 do while 循环(即您知道您将至少执行一次逻辑。)

System.out.println("Please enter the second number: ");
do {
     int denominator = scanner.in();
     if (denominator == 0) System.out.println("Please enter a non-zero number: ");
} while (denominator == 0);
于 2011-06-10T00:34:36.857 回答
3
int denominator = 0;
do {
    System.out.print("Please enter the second number: ");
    denominator = scanner.nextInt();
} while (denominator == 0);
于 2011-06-10T00:38:06.543 回答
1
System.out.print("Please enter the second number: ");
int denominator = scanner.nextInt();
while (denominator == 0) {
    System.out.print("Please enter a non-zero number: ");
    denominator = scanner.nextInt();
}
于 2011-06-10T00:30:54.710 回答