简体   繁体   中英

reading in values to insert in a 2d array

I am working on an assignment in which I need to read in sample input from a file and insert it into a 2D array. Here is an example of input:

5 6
1 3 4 B 4 3
0 3 5 0 0 9
0 5 3 5 0 2
4 3 4 0 0 4
0 2 9 S 2 1

The 5 and 6 are the dimensions of the array. The user must be able to input many arrays like this one at once, the program ends when the user inputs -1. This is the code I have so far that doesn't seem to be working as it should(I print out the array to make sure the code works):

public static void main (String[] args){
    Scanner sc = new Scanner(System.in);
    int arHeight = sc.nextInt();
    int arWidth = sc.nextInt();
    sc.useDelimiter(" ");
    String[][] map = new String[arHeight][arWidth];

        for(int i=0; i<arHeight; i++){
            for(int j=0; j<arWidth; j++){
                map[i][j] = sc.nextLine();
            }//end inner for
        }//end outter for 

            for(int i=0; i<arHeight; i++){
            for(int j=0; j<arWidth; j++){
                System.out.print(map[i][j] + " ");
            }//end inner for
        }//end outter for 
    }

The assignment states that I cannot use recursion and that I must use 2D arrays. I have looked at other questions but still can't seem to figure it out. Thanks for the help!!

you read the whole line i*j times

    for(int i=0; i<arHeight; i++){
        for(int j=0; j<arWidth; j++){
            map[i][j] = sc.nextLine();

also you keep al the data in a string array and I don't know why. Here is the solution:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int arHeight = sc.nextInt();
    int arWidth = sc.nextInt();

    int[][] map = new int[arHeight][arWidth];

    for(int i=0; i<arHeight; i++){
        for(int j=0; j<arWidth; j++){
            map[i][j] = sc.nextInt();
        }//end inner for
    }//end outter for

    for(int i=0; i<arHeight; i++){
        for(int j=0; j<arWidth; j++){
            System.out.print(map[i][j] + " ");
        }//end inner for
    }

}

Then try to use

char[][] map = new char[arHeight][arWidth];

and in the for loop:

if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0);

This way you should read all the chars which are not " ".

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