帮助使用while循环和if语句

时间:2011-06-10 00:26:53

标签: java if-statement while-loop divide-by-zero

我正在尝试编写一个程序,从用户那里读取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,请让用户输入不同的数字?

3 个答案:

答案 0 :(得分:4)

这不是您问题的答案,但您需要将这些数字中的至少一个转换为双倍。现在你只是做整数除法,即5/3 = 1.你可以用double num =(double)分母来做到这一点。

其次,这是一个很好的使用do while循环。继续询问数字,直到它不是0.你知道你想要一个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);

答案 1 :(得分:3)

int denominator = 0;
do {
    System.out.print("Please enter the second number: ");
    denominator = scanner.nextInt();
} while (denominator == 0);

答案 2 :(得分: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();
}