2017-10-12 228 views
0

我一直在試圖找出這個問題的答案有什麼問題。真的需要幫助!任何幫助表示讚賞!由於JAVA - For循環和If else語句

問題

  • 您可以輸入兩個整數(A和B),並
  • ,程序會從數字打印到數字B如果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(); 
    } 
    

    }

回答

5

我做了一些修改,以你目前的嘗試,這是不遠處被功能。首先,我使用循環來提示用戶輸入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); 
} 
+0

'while(true)'和'break'不是'很好的做法','do/while'是爲:) – azro

+0

@azro重構,謝謝,你剛剛刪除了一行不必要的代碼。現在讓我們考慮一種用單行lambda替換整個事物的方法;-) –

0

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

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); 
      } 
     } 
    } 
} 
1

要允許用戶輸入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 
    } 
}