我想要一个代码,告诉你输入两个数字,直到你输入两个偶数倍的数字。我正在为这个任务使用一个循环语句,当我运行我的代码并输入两个不是偶数的数字时,它会一直说"请输入偶数倍数"。请帮我。 Thx提前。这是我的代码。
public class looper {
public static void main (String[] args) {
float firstNumber = 0;
float secondNumber = 0;
float finalNumber = 0;
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.println("Enter your first number.");
firstNumber = input.nextFloat();
input.nextLine();
System.out.println("Enter your second number.");
secondNumber = input.nextFloat();
finalNumber = firstNumber % secondNumber;
System.out.println(secondNumber + " and " + firstNumber + " are even multiples.");
while(finalNumber != 0) {
System.out.println("Please enter even multiples.");
}
}
}
答案 0 :(得分:0)
您需要设置finalNumber
的值,使其满足while
循环的终止条件。你可能想做这样的事情(我没有编译这段代码!):
while (finalNumber != 0){
System.out.println("Enter your first number.");
firstNumber = input.nextFloat();
input.nextLine();
System.out.println("Enter your second number.");
secondNumber = input.nextFloat();
finalNumber = firstNumber % secondNumber;
}
System.out.println(secondNumber + " and " + firstNumber + " are even multiples.");
答案 1 :(得分:0)
在计算while
循环的条件时要小心。如果不更新用于检查循环内部的变量,则会进入无限循环。
这里重要的是你需要用户提供两个值。你根本不需要第三个变量来跟踪它,这取决于你如何写它,但它可以用这种方式编写:
value1 % value2 == 0
...
System.out.println("Enter your first number.");
firstNumber = input.nextFloat();
input.nextLine();
System.out.println("Enter your second number.");
secondNumber = input.nextFloat();
while(firstNumber % secondNumber != 0) {
System.out.println("Please enter two numbers that are multiples of each other.");
System.out.println("Enter your first number.");
firstNumber = input.nextFloat();
input.nextLine();
System.out.println("Enter your second number.");
secondNumber = input.nextFloat();
}
// afterwards, print whatever message you require.
答案 2 :(得分:0)
如果你没有使用的问题,那么使用if条件。制作两个独立的功能。一种是检查调用其他条件的条件以获得结果。这是一个示例代码。希望,它会帮助你。对不起,可能是英语不好。
public class Looper
{
public static void main (String[] args)
{
Looper looper = new Looper();
looper.runTest();
}
public void runTest()
{
float finalNumber = getResult();
System.out.println("finalNumber: " + finalNumber);
if(finalNumber != 0.0)
{
System.out.println("Please enter even multiples.");
runTest();
}
}
public float getResult()
{
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.println("Enter your first number.");
float firstNumber = input.nextFloat();
input.nextLine();
System.out.println("Enter your second number.");
float secondNumber = input.nextFloat();
float finalNumber = firstNumber % secondNumber;
System.out.println(secondNumber + " and " + firstNumber + " are even multiples.");
return finalNumber;
}
}
答案 3 :(得分:-1)
您需要使用if语句,因为您只想告知用户输入的数字不正确
do{
System.out.println("Enter your first number.");
firstNumber = input.nextFloat();
input.nextLine();
System.out.println("Enter your second number.");
secondNumber = input.nextFloat();
finalNumber = firstNumber % secondNumber;
if(finalNumber!=0)
System.out.println("values not correct ");
}while(finalNumber!=0);