除了代码的最后部分之外,我的 Java 代码中一切都运行良好。所以基本上我不知道如何打印出用户号码(如果它是相同的)。例如,我提示用户输入起始数字和结束数字(整数)。假设用户输入相同的整数“10”作为起始号码,“10”作为结束号码。我希望输出仅为“10”,仅打印一次。我已经尝试了所有我能想到的方法,包括尝试 While 循环、Do-While 循环和 For 循环,但我就是无法弄清楚?
------------------------下面的JAVA代码-------------------- -----------------------
import java.util.Scanner;
public class LoopsAssignment {
public static void main(String[] args) {
// input Scanner
Scanner input = new Scanner(System.in);
// ask user for a starting number and a ending number
System.out.println("Now I'll print whatever numbers you'd like!");
System.out.println("Give me a starting number: ");
startNum = input.nextInt();
System.out.println("Give me an ending number: ");
endNum = input.nextInt();
// count the users range of numbers
System.out.println("I counted your range of numbers: ");
int a = startNum;
int b = endNum;
while (a <= b) {
System.out.println(a);
a = a + 1;
}
while (a >= b) {
System.out.println(a);
a = a - 1;
}
while (a == b) {
System.out.println(a);
}
}
}
---------------------输出如下---------------------- ------------------------------------------
现在我将打印您想要的任何数字! 给我一个起始号码: 10 给我一个结束号码: 10 我算了一下你的数字范围: 10 11 10
----jGRASP:操作完成。
最佳答案
您可以按如下方式重组代码:
while (a < b) {
System.out.println(a);
a = a + 1;
}
while (a > b) {
System.out.println(a);
a = a - 1;
}
if (a == b) {
System.out.println(a);
}
关于java - 如何使用Java中的嵌套循环仅打印一次单个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480436/