簡體   English   中英

在 while 循環中打印數組

[英]Printing an array in a while loop

我試圖在用戶輸入 y 或 Y 時使用一次方法調用打印我的數組。我不知道如何讓數組只打印一次。

我已經研究並嘗試調整我自己的代碼,但我迷路了。

public class Lab10p1 {
public static final int ROW = 5;
public static final int COL = 6;
public static final int MIN = 0;
public static final int MAX = 100;

/**
* @param args the command line arguments
*/
public static void main(String[] args) 
{
    Scanner scan=new Scanner(System.in);
    System.out.println("Do you want to start Y/N?");
    char c =scan.next().charAt(0);

    while(c=='y'||c=='Y')
    {
        int[][] a = new int[ROW][COL]; 
        randArray(a, ROW, COL, MIN, MAX);
    }
}

public static void randArray(int[][] matrix, int row, int col, int low, int up)
{     
    Random rand = new Random();   
    for (int r = 0; r < row; r++)
    {          
        for (int c = 0; c < col; c++)   
        {         
            int are=matrix[r][c] = rand.nextInt(up - low + 1) + low; 
            System.out.print(" "+are); 
        }       
        System.out.println();
    }
}

預期的輸出是

你想繼續嗎(是/否):是
數組元素為:
12 31 12 21 45 23
32 12 67 54 35 67
34 54 33 34 53 34
23 34 43 23 45 78
23 54 89 76 54 34

實際結果是無限循環打印6x5數組

您應該使用if而不是while 如果用戶輸入Yy ,則循環將永遠不會完成,因為c在循環內從未設置為Yy任何其他值,因此循環條件始終為真。

如果您想在每個打印的數組之后再次詢問用戶,您必須將問題包含在循環中,但在這種情況下,我更喜歡do while循環。

一旦你打印了array 提示用戶再次輸入字符,因此如果他/她再次輸入 Y,則再次打印數組,例如:

while(c=='y'||c=='Y')
{
    int[][] a = new int[ROW][COL]; 
    randArray(a, ROW, COL, MIN, MAX);
    System.out.println("Do you want to start Again Y/N?");
    c = scan.next().charAt(0);
}

或者,如果您希望程序只運行一次,則將while替換為if

這是因為您只輸入了 'c' 的值一次並不斷迭代它,現在它進入無限循環,因為 'c' 的值根本沒有改變。

char c =scan.next().charAt(0);
int[][] a;
while(c=='y'||c=='Y')
{

a = new int[ROW][COL]; 
randArray(a, ROW, COL, MIN, MAX);
c =scan.next().charAt(0);
}

此外,您不必每次都重新聲明二維數組。


此外,您可以使用更適合這種情況的 do-while 循環。

兩種方式

 if(c=='y'||c=='Y')
{
    int[][] a = new int[ROW][COL]; 
    randArray(a, ROW, COL, MIN, MAX);
}

或者

 while(c=='y'||c=='Y')
{
    int[][] a = new int[ROW][COL]; 
    randArray(a, ROW, COL, MIN, MAX);
    break;
}

暫無
暫無

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

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