【发布时间】:2015-02-22 20:02:47
【问题描述】:
我制作了一个程序,提示用户输入两个数字。如果这些数字是偶数倍,我将显示两个数字之间的所有奇数。如果这些数字不是偶数,我会要求用户重新输入这两个数字。我已经使用 while 循环成功地制作了这个程序。但我想知道如何使用“for”循环来制作这样的程序。这是我使用 while 循环的原始代码。所有提示和建议都会有所帮助。
/**
* Description: This program takes two integers entered by the user and
* displays the odd numbers between the integers if the integers entered
* are even multiples. If the integers entered are not even multiples,
* the program will prompt the user to re enter the integers.
*/
/**
* This is the main loops class. This class
* includes the main method as well
* as the program method.
*/
public class loops {
/**
* This is the main method. It provides an
* entry into the program.
*/
public static void main (String []args) {
loops lps = new loops();//Instantiating loops class.
lps.program();//Invoking the program method on the loops class.
}
/**
* This is the program method. This
* method will carry out the program
* functions.
*/
public void program() {
/**
* Declaring variables that
* will be used in the program.
*/
int firstNumber;
int secondNumber;
int finalNumber;
java.util.Scanner input=new java.util.Scanner(System.in);//Using the Java utility scanner.
try {//Try statement. Used to handle exceptions.
do {//Using a do-while loop.
/**
* Prompting the user to enter two
* integers. Then taking the remainder
* of the integers.
*/
System.out.println("Enter your first number.");
firstNumber = input.nextInt();
input.nextLine();
System.out.println("Enter your second number.");
secondNumber = input.nextInt();
finalNumber = firstNumber % secondNumber;
if(finalNumber !=0) {//If the remainder is not zero, these statements should be printed.
System.out.println("Please enter even multiples.");
System.out.println("(Try switching the order in which you input the numbers)");
}
}
/**
* This is a while loop that will keep prompting the
* user to enter two integers until the remainder
* of the two integers is 0 and the two numbers
* entered are even multiples.
*/
while (finalNumber !=0);
if(finalNumber == 0) {//The following code will be executed only if the remainder is 0.
System.out.println("Displaying all odd numbers between " + firstNumber + " and " + secondNumber);
int number = secondNumber;//Declaring number variable, giving it value of secondNumber.
/**
* This is a while loop that will display all the odd
* numbers between the two integers entered.
*/
while(number <= firstNumber){
if (number % 2 != 0) {
System.out.println(number);
}
number++;
}
}
}
catch (java.util.InputMismatchException e) { //Catching multiple exceptions.
System.out.println("Please enter whole numbers.");
}
catch ( java.lang.ArithmeticException e) { //Catching multiple exceptions.
System.out.println("Please enter whole numbers.");
}
}
}
【问题讨论】:
-
当你说“这是一个不断提示用户的 while 循环......”时,你知道这不是一个单独的循环,对吗?这是上面 do/while 循环的最后一部分。
-
哦,是的,我明白了。感谢您指出这一点。