![](/img/trans.png)
[英]Trying to print an increasing number pyramid with lines on the sides, using only nested for loops (Java)
[英]How to print single number only once using nested loops in Java?
除了在代碼的最后,我的 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);
}
您可以使用for loop
:
public static void printRange(int minInclusive, int maxInclusive) {
for (; minInclusive <= maxInclusive; minInclusive++)
System.out.println(minInclusive);
}
所以你要么在計數,要么在計數,要么只有一個。
所以
int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
System.out.println(a);
a = a + step;
}
System.out.println(b);
或者在for
循環中間放置一個break
。 還有+=
,還有一些我們可以做的更傳統的事情。
int step = endNum>startNum ? +1 : -1;
for (int i=startNum; ; i+=step) {
System.out.println(i);
if (i == endNum) {
break;
}
}
問題出在您使用“ >=
”和“ <=
”的前兩個while
循環中。 您可以從條件中刪除"="
。
但是,您可以按照其他評論中的建議改進您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.