嗨,我是编程新手,所以请不要因为我的愚蠢问题而笑。
我编写的程序要求用户输入一个数字,而不是程序应该输出从 0 到输入的数字的所有数字(不管它是正数还是负数)。我尝试了 3 个不同的版本
这是我的代码:
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
int num = PutiL.validNum(min, max, "number");
//this my utility methode which check if number is in range and if it is not a double or letter
int i = 0, z;
int y = 0;
//3rd version
while (i <= num) {
for (z = 0; z < 4; z++) {
System.out.print(i + " ");
i++;
}
System.out.println();
}
//2nd version
if (num > 0) {
for (i = 0; i <= num; y++) {
for (z = 0; z < 4; z++) {
System.out.print(i + ",");
i++;
}
System.out.println();
}
} else {
for (i = 0; i > num; y--) {
for (z = 0; z < 4; z++) {
System.out.print(i + ",");
i--;
}
System.out.println();
}
}
//1st version`enter code here`
if (num > 0) {
for (i = 0; i <= num; i++)
{
System.out.print(i + ",");
}
} else {
for (i = 0; i >= num; i--) {
System.out.print(i + ",");
}
}
System.out.println();
问题是代码不会在用户输入数字后立即停止。有人会提示我出了什么问题,因为我没有更多的想法。
这是 Putil 方法
public static int validNum(int min, int max, String words) {
int num;
do {
System.out.println("Please enter " + words);
while (!kb.hasNextInt()) {
System.out.println("Please re-enter ");
kb.nextLine();
}
num = kb.nextInt();
if (num < min || num > max) {
System.out.println("Not in range - re-enter\tproper range is "
+ min + " - " + max);
}
} while (num < min || num > max);
return num;
}