[英]Issue with reading values from Multi-dimensional array
我正在研究一個問題,我需要將用戶輸入的坐標(用空格分隔)轉換為多維數組。 我試圖將'x'和'y'值分開,並將它們分別存儲在單維數組中,例如x [i]和y [i]。
我在這里遇到的問題是我無法從數組中讀取'y'值。 當我試圖輸出包含y值的數組時,它只顯示0。 請幫助我解決這個問題。 請在下面找到我的代碼。
(注意:N =多維數組中的行數,列固定為2)(抱歉,忘記R,用於其他目的)
public class Read{
public static void main(String[] args) {
int N = 1, R=1;
double AoN=1;
float d=0 , e=0, s=0, length=0;
Scanner in = new Scanner(System.in);
int[] arr = new int[2];
System.out.println("Enter values of N and R separated by space: ");
for (int i=0;i<arr.length;i++) {
arr[i]=in.nextInt();
if (arr[0]>=1 && arr[0]<=100) {
N=arr[0]; //storing N
}
R=arr[1]; //storing R
}
float[ ][ ] arr1 = new float[N][2];
System.out.println("Enter Coordinates seperated by spaces: ");
for(int i=0; i<N;i++) {
for (int j=0;j<2;j++) {
arr1[i][j]=in.nextFloat();
//System.out.println(arr1[i][j]);
}
}
float[] x = new float[N];
float[] y = new float[2]; // I've given 2 here coz the coordinates are always x and y. please correct me if im wrong.
for(int i=0; i<N;i++) {
x[i] = arr1[i][0];
System.out.println(x[i]);
}
for (int j=0;j<N;j++) {
y[j] = arr1[0][j];
System.out.println(y[j]);
}
輸入:
2 1 (N, R)
0 0 (x1, y1)
1 3 (x2, y2)
輸出:
0.0 (x1)
1.0 (x2)
0.0 (y1)
0.0 (y2)
包含'y'值的數組的輸出始終為0(應為0和3)。 善意的幫助。 謝謝。
我覺得你這里有個bug ...
for (int j = 0; j < N; j++) {
y[j] = arr1[0][j]; // <<< HERE!!
System.out.println(y[j]);
}
我想你的意思是......
for (int j = 0; j < N; j++) {
y[j] = arr1[j][1];
System.out.println(y[j]);
}
使用您輸入的參數,當代碼到達“float [] x = ...”位時,“arr”的狀態為......
arr = [2, 1]
arr1 = [[0.0, 0.0], [1.0, 3.0]]
第二個塊總是選擇2d數組的第一個元素,每個“j”值都為“0”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.