[英]Create a 2D Array that has different size of columns using 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')
val
是int
,不要將它與一個換行符比較。 將其更改為:
while (val != -1)
並輸入-1
停止。
如果用戶可以輸入 -1 作為有效元素,則可以將val
更改為字符串,替換sc.nextInt()
調用,並將輸入解析為 int。 確保使用.equals()
而不是==
比較字符串。
換行符 ('\\n') 的 ASCII 值是 10。因此,如果您選擇繼續使用當前代碼,則必須通過輸入值10
來停止循環(這會很奇怪,而且 10 可以'不會作為有效元素添加)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.