我正在编写一个程序,要求用户输入两个整数,总共十次。
接下来,程序需要评估第一个整数是否是第二个整数的倍数。
如果第一个是第二个的倍数,那么程序应该打印出“true”,如果不是那么它应该打印出“false”。
这是我的代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0; // Initializes the counter
System.out.printf("Enter first integer: "); // asks the user for the first integer
int number1 = input.nextInt(); // stores users input for the first integer
System.out.printf("Enter second integer: "); // asks the user for the second integer
int number2 = input.nextInt(); // stores the users input for the second integer
while (counter <= 10) // starts a loop that goes to 10
{
if (number1 & number2 == 0) // checks to see if number1 is a multiple of number2
System.out.print("true"); // if so then print out "true"
else
System.out.print("false"); // otherwise print out "false"
}
} // end class
沿着这条线的某处,我的代码正在破碎。有没有人可以提供帮助,或者至少指出我正确的方向?
答案 0 :(得分:3)
您需要读取两次输入10次。并测试number1
是number2
的倍数。像
public static void main(String str[]) throws IOException {
Scanner input = new Scanner(System.in);
for (int counter = 0; counter < 10; counter++) {
System.out.printf("Enter first integer for counter %d: ", counter);
int number1 = input.nextInt();
System.out.printf("Enter second integer for counter %d: ", counter);
int number2 = input.nextInt();
// Since you want to print true if number1 is a multiple of number2.
System.out.println(number1 % number2 == 0);
}
}
答案 1 :(得分:1)
&
是按位逻辑AND函数。我很确定不会做你想做的事。好像你想要MODULO运算符%
。
E.g。使用number1%number2。而不是number1&amp;数字2
while (counter <= 10) // starts a loop that goes to 10
{
if (number1 % number2 == 0) // checks to see if number1 is a multiple of number2
System.out.print("true"); // if so then print out "true"
else
System.out.print("false"); // otherwise print out "false"
}