簡體   English   中英

如何使用 Java 中的 Scanner 創建具有指定行大小的二維數組而不指定列大小?

[英]How to create 2D array with specified row size without specifying columns size using Scanner in Java?

這是一個java代碼

    public class Demo { 
        public static void main(String[] args) 
        { 
            Scanner sc=new Scanner (System.in);
            System.out.println("enter the no of rows");
            int n =sc.nextInt(); 
            ArrayList<Integer>[] al = new ArrayList[n]; 
            for (int i = 0; i < n; i++)
            { 
                al[i] = new ArrayList<Integer>(); 
            } 
            System.out.println("enter the value");
            int val=0;
            for (int i = 0; i < n; i++) 
            {   
                while(val!='\n')
                {
                    val=sc.nextInt();       
                    al[i].add(val);
                }
            }
            for (int i = 0; i < n; i++) { 
                  for (int j = 0; j < al[i].size(); j++) { 
                    System.out.print(al[i].get(j) + " "); 
                 } 
                System.out.println(); 
             } 
        } 
     }

我試圖通過使用 ArrayList 數組來實現。 但是在從用戶那里獲取輸入時會導致無限輸入

while(val!='\n')

valint ,不要將它與一個換行符比較。 將其更改為:

while (val != -1)

並輸入-1停止。

如果用戶可以輸入 -1 作為有效元素,則可以將val更改為字符串,替換sc.nextInt()調用,並將輸入解析為 int。 確保使用.equals()而不是==比較字符串。


換行符 ('\\n') 的 ASCII 值是 10。因此,如果您選擇繼續使用當前代碼,則必須通過輸入值10來停止循環(這會很奇怪,而且 10 可以'不會作為有效元素添加)。

暫無
暫無

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

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