我正在做一个简单的分数测试课。我希望我的程序能够做到这一点。
如果用户输入0>循环重复,直到用户输入不是0的数字
在我的课堂上,它没有这样做。我尝试将其与do while
条件与if
语句混合,并初始化语句true
或false
。我卡住了所以请我帮忙。
这里我的分数类:
import java.util.*;
public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
boolean valid = true;
int num, den;
den = 0;
do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}
} while (den != 0 && !valid);
System.out.println("Decimal is " + result(num, den));
}
public static double result(int x, int y) {
return (x / y);
}
}
答案 0 :(得分:1)
问题并不完全清楚,但我认为你要求每当分母变为零时继续循环,否则计算答案和返回值。我根据
对您的代码进行了一些更改public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
boolean valid = true;
int num, den;
den = 0;
while(den == 0) {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}
}
System.out.println("Decimal is " + result(num, den));
return;
}
public static double result(int x, int y) {
return ((1.0)*x / y);
}
}
答案 1 :(得分:0)
将main方法中的代码更改为:
Scanner input = new Scanner(System.in);
int num, den;
do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den!=0)
System.out.println("Decimal is " + result(num, den));
else
System.out.println("Denominator shouldnt be 0");
} while (den == 0);
input.close();
答案 2 :(得分:0)
我只想分开您的输入验证:
System.out.println("Please enter the numerator: ");
num = input.nextInt();
do{
System.out.println("Please enter the denominator: ");
System.out.println("denominator cannot be zero");
den = input.nextInt();
} while (den == 0);
System.out.println("Decimal is " + result(num, den));
如果你需要对你的分子进行输入验证,那就做一下。您的有效布尔值也始终为true。永远不要修改为假。如果x为真,则逻辑(x ^ True)将始终为。