【发布时间】:2015-10-27 12:14:06
【问题描述】:
使用while循环不断要求用户输入顺序 数字,直到用户确实以正确的顺序给出了两个数字(首先 小于秒
嗨!我是java的初学者,我有这个代码,但我不能循环“错误”消息。它只打印了 2 次p>
import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type two numbers:");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
if (num1 < num2) {
int counter = num1;
while (counter <= num2) {
System.out.print(counter + " ");
counter = counter + 1;
}
}
else {
System.out.println("Error: the first number must be smaller than the second");
System.out.print("Please type two numbers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
}
}
}
【问题讨论】:
-
您能否让人们知道您使用了哪些输入?
-
你的实际问题是什么,对我来说它正在工作。
-
你需要另一个循环,
if/else子句在其中。 -
嗨,这是我输入的内容:请输入两个数字:3 1 错误:第一个数字必须小于第二个数字 请输入两个数字:6 1
-
一个简单的解决方案是将
while(num1 < num2) { // display error and ask again }放在开头,然后打印计数器循环。
标签: java loops if-statement while-loop