我在为程序找到所有可能的奇数时遇到困难。我需要使用while循环来查找所有奇数,但我不知道如何将其打印出来。我不知道我在这个区块while((num1+num2)%2==0)
做错了什么,因为那只是一个猜测。该程序的概要是让用户输入2个数字,这是另一个数字的偶数倍。我也不确定那部分是怎么回事。找到2个数字是另一个数字的偶数倍后,我应该显示两个数字之间的所有奇数。非常感谢。
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
答案 0 :(得分:1)
这样的事情怎么样:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
将电流设置为等于num1,继续循环,同时电流小于num2。对于每次迭代检查当前是否为奇数并且如果是,则输出它。将电流增加一个。