簡體   English   中英

JAVA-For循環和If else語句

[英]JAVA - For loop and If else statement

我一直試圖找出問題的答案出了什么問題。 真的需要幫助! 任何幫助表示贊賞! 謝謝

  • 您可以輸入兩個整數(a和b),並且
  • 如果a<b ,程序將從數字a打印到數字a<b
  • 如果a>b ,程序將從b打印到a。
  • 如果b is the same as a ,則程序將要求用戶輸入另一個數字b,直到它不等於a。

     Scanner sc = new Scanner(System.in); System.out.println("Enter a: "); int a = sc.nextInt(); System.out.println("Enter b: "); int b = sc.nextInt(); if(a > b) { for(int i = b; b >= a; b--) { System.out.println(b); } } else if (a < b) { for(int i = a; a <= b; a++) { System.out.println(i); } } else { System.out.println("Enter another number b: "); int numberb = sc.nextInt(); } 

    }

我對您當前的嘗試做了一些更正,這與功能的實現並不遙不可及。 首先,我使用循環不斷提示用戶輸入b數字,直到a不等於b為止。 握住不同的ab ,然后執行一個循環以打印出從最小到最大(包括兩端)的數字范圍。

Scanner sc = new Scanner(System.in);
System.out.println("Enter a: ");
int a = sc.nextInt();
int b;
do {
    System.out.println("Enter b: ");
    b = sc.nextInt();
} while (b == a);

for (int i=Math.min(a, b); i <= Math.max(a,b); ++i) {
    System.out.println(i);
}

要允許用戶輸入b直到與a不同,可以使用do while loop

Scanner sc = new Scanner(System.in);
System.out.println("Enter a: ");
int a = sc.nextInt();
int b = 0;
do {
    System.out.println("Enter b: ");
    b = sc.nextInt();
} while (a == b);

然后打印即可:

for (int i=Math.min(a, b); i <= Math.max(a,b); ++i) {
    System.out.println(i);
}

或更正您的代碼:

 if (a > b) {
    for (int i = b; i <= a; i++) {   // i is the index to change
        System.out.println(i);       // use i
    }
} else if (a < b) {
    for (int i = a; i <= b; i++) {   // i is the index to change
        System.out.println(i);       // use i
    }
}

您的for循環迭代是錯誤的。 對於您的第三個條件,我進行了一些更改。 更改您的代碼:

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        test t = new test();
        System.out.println("Enter a: ");
        int a = sc.nextInt();
        System.out.println("Enter b: ");
        int b = sc.nextInt();
        if(a==b) {
            do {
                System.out.println("Both are same enter again");
                b = sc.nextInt();
            }while(a==b);
            t.loop(a, b);
        }else {
            t.loop(a,b);
        }
    }
    void loop(int a, int b) {
        if(a > b) {
            for(int i = b; i <= a; i++) {
                System.out.println(i);
            }
        } else if (a < b) {
            for(int i = a; i <= b; i++) {
                System.out.println(i);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM