简体   繁体   中英

Filling a multidimensional array using loops (NetBeans IDE 8.2)

I'm trying to fill two 2 by 2 arrays, one being a String, the other an integer.

package javaapplication24;
import java.util.Scanner;
/**
 *
 * @author Joshua
 */
public class JavaApplication24 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String[][] arrString;
arrString = new String[2][2];
int[][] arrInt;
arrInt = new int[2][2];
for(int a = 1; a != 3; a++){
for(int b = 1; b != 3; b++){
System.out.println ("Enter a \"String\" for " +a+ " - " +b+ ".");
arrString[a][b] = sc.next();
}}
for(int a = 1; a != 3; a++){
for(int b = 1; b != 3; b++){
System.out.println ("Enter a \"Integer\" for " +a+ " - " +b+ ".");
arrInt[a][b] = sc.nextInt();  
}}
System.out.println (arrString[1][1] = arrString[1][2] + arrString[2][1] + arrString[2][2]);
System.out.println (arrInt[1][1] + arrInt[1][2] + arrInt [2][1] + arrInt[2][2]);
}}

Every single time that I try to change something with the loops it seems to only go to 1 - 2 and then gives me a error on line 28.

I have no clue what else I could do to fill the rest of the array slots.

Any help appreciated.

Change the last lines from this:

System.out.println (arrString[1][1] = arrString[1][2] + arrString[2][1] + arrString[2][2]);
System.out.println (arrInt[1][1] + arrInt[1][2] + arrInt [2][1] + arrInt[2][2]);

to this:

System.out.println (arrString[0][0] = arrString[0][1] + arrString[1][0] + arrString[1][1]);
System.out.println (arrInt[0][0] + arrInt[0][1] + arrInt [1][0] + arrInt[1][1]);

Arrays indexes start from 0 and both matrix lengths are 2 so the indexes for both matrix will be: 00,01,10,11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM