我想做一些事情,如果我鍵入“1”,則數字將升序(x ),如果我鍵入“2”,則數字將降序。x 作業正常,但如果我使用 x--,它將無限回圈
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print("Enter starting loop:");
int start = scan.nextInt();
System.out.print("Enter ending loop:");
int end = scan.nextInt();
System.out.print("Choose Order:");
int n = scan.nextInt();
if (n==1) {
for (int x=start;x<=end;x--){
System.out.print(x "\t");
}
}
}
uj5u.com熱心網友回復:
對于第二個回圈,將其更改為 x>=end 而不是當前的 x<=end 。基本上你必須做兩個 for 回圈:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print("Enter starting loop:");
int start = scan.nextInt();
System.out.print("Enter ending loop:");
int end = scan.nextInt();
System.out.print("Choose Order: ");
int n = scan.nextInt();
if(n==1)
{
for (int x=end;x>=start;x--){ //If they want to go from end to 0
System.out.print(x "\t");
}
else
{
for (int x=start;x<=end;x ){ //So when they want it to go from 0 to end
System.out.print(x "\t");
}
uj5u.com熱心網友回復:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter starting loop:");
int start = scan.nextInt();
System.out.print("Enter ending loop:");
int end = scan.nextInt();
System.out.print("Choose Order:");
int n = scan.nextInt();
boolean isAscending = n == 1;
for (int i = start; (isAscending) ? i <= end : i >= end; i = (isAscending) ? i 1 : i - 1) {
System.out.print(i "\t");
}
}
示例:從 1 到 10,順序為 1
Enter starting loop:1
Enter ending loop:10
Choose Order:1
1 2 3 4 5 6 7 8 9 10
示例:從 10 到 1,順序為 2
Enter starting loop:10
Enter ending loop:1
Choose Order:2
10 9 8 7 6 5 4 3 2 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/324393.html
上一篇:Eclipse文字變大了
