[英]User input numbers into a 2 dimensional array in java
我在用Java輸入用戶時遇到麻煩,希望任何人都可以幫助:)用戶聲明2d數組的大小(數字d是方陣的邊),然后輸入數字“ n”,該數字告訴編程將有多少個數字輸入,然后需要輸入這些數字(例如,如果n = 4,則輸入必須類似:5 17 320。我已經為單行數組編寫了相同的東西
for(i=0;i<=n;i++) {
arr[i]=sc.nextInt();
}
但是在為2d數組做基本相同的操作時遇到麻煩。 有任何想法嗎?
使用兩個嵌套循環和類似arr[i][j]
索引
抱歉,我還沒有評論的能力,所以我將其發布為答案。 本質上,您需要如上所述使用嵌套的for循環。 我將為您提供基本模板
for (int i = 0; i < length; i ++){
for (int j = 0; j < width; j ++){
if (counter < userInput){
counter++;
arr[i][j] = value;
} else {
break;
}
}
}
int d=sc.nextInt(); //length of rows and columns
int n=sc.nextInt(); //user input how many numbers
int[][] array=new int[d][d]; //length and heigth of array
for (int i=0;i<d;i++) {
for(int j=0;j<d;j++) {
array[i][j]=sc.nextInt();
}
}
int distance=0;
int c=0;
for(int i=0;i<d;i++){
for(int j=0;j<d;j++){
array[i][j]=c;
c++;
}
}
最后,我只是想讓整個事情都看到,如果我錯過了其他地方的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.