2017-01-06 16 views
-1

我已經嘗試了這樣的其他問題,但似乎沒有匹配它。如果用戶在控制檯中排序數字後輸入Y,我希望它重複。 這裏是代碼:試圖重複這個程序,如果用戶說Y

package compsorter; 
import java.util.Scanner; 
public class Ascending_Order 
{ 
    public static void main(String[] args) 
    { 
    int n, temp; 
    Scanner s = new Scanner(System.in); 
    System.out.print("Enter no. of elements you want in array:"); 
    n = s.nextInt(); 
    int a[] = new int[n]; 
    System.out.println("Enter all the elements:"); 

    for (int i = 0; i < n; i++) 
    { 
     a[i] = s.nextInt(); 
    } 
    for (int i = 0; i < n; i++) 
    { 
     for (int j = i + 1; j < n; j++) 
     { 
      if (a[i] > a[j]) 
      { 
       temp = a[i]; 
       a[i] = a[j]; 
       a[j] = temp; 
      } 
     } 
    } 
    System.out.print("In Ascending Order:"); 
    for (int i = 0; i < n - 1; i++) 
    { 
     System.out.print(a[i] + ","); 
    } 
    System.out.print(a[n - 1]); 
    s.close(); 
} 
} 

謝謝!

+0

你可以使用一個做的時候做到這一點! –

+0

你應該瞭解while和do ... while循環。 –

回答

0

這樣,

do{ 
    //code here 
    //take input from user 'Y' or 'N' 
    }while(condition); 
0

您可以後 Scanner s = new Scanner(System.in);

} while(s.readLine().equals("Y"))s.close();

0

而這reaso儘量做到把 do {有這樣的例子:link

0

你可以用while循環來做到這一點。 下面是你應該有的主要方法程序。

public static void main(String[] args) { 
    String flag = "Y"; 
    Scanner s = new Scanner(System.in); 
    while (true) { 

    if ("Y".equalsIgnoreCase(flag)) { 
    int n, temp; 

    System.out.print("Enter no. of elements you want in array:"); 
    n = s.nextInt(); 
    int a[] = new int[n]; 
    System.out.println("Enter all the elements:"); 

    for (int i = 0; i < n; i++) { 
     a[i] = s.nextInt(); 
    } 
    for (int i = 0; i < n; i++) { 
     for (int j = i + 1; j < n; j++) { 
     if (a[i] > a[j]) { 
      temp = a[i]; 
      a[i] = a[j]; 
      a[j] = temp; 
     } 
     } 
    } 
    System.out.print("In Ascending Order:"); 
    for (int i = 0; i < n - 1; i++) { 
     System.out.print(a[i] + ","); 
    } 
    System.out.print(a[n - 1]); 
    System.out.println(); 
    System.out.print("Do you want to continue Y/N?"); 
    flag = s.next(); 

    } else { 
    break; 
    } 
} 
s.close(); 
} 
相關問題