简体   繁体   中英

How to scanning files and assign values to a 2D array in java

I'm a new learner to java and I'm scanning a .dat file and I want to print it out as a table in blueJ. My codes are as follows:

Scanner sc = new Scanner(new File ("test01.dat")); 
for (int r = 0; r < 6; r++){
    for (int c = 0; c < 3; c++){
        int temp = 0;
        temp = sc.nextInt();
        tri[r][c] = temp;
        System.out.print(tri[r][c]+" ");
    }
    System.out.println();
    sc.nextLine();
}

I almost get there but my problem is that my result printed out is 19 numbers including a zero at the end.(It was supposed to be 18 numbers with no zero at the end) How can I get rid of that zero? Oh and in addition, my input is just a column of 18 numbers and I'm changing it to a table with 6 rows and 3 columns. For more information, here is the link of my file: https://onedrive.live.com/redir?resid=B6E07F4C7635D773!4577&authkey=!AL9Zw4b4CWlS630&ithint=file%2cdat Thanks for all the comments and finally I found what I need~(^o^)~

The problem is using sc.nextLine after sc.nextInt.

Scanner sc = new Scanner(new File ("test01.dat")); 
for (int r = 0; r < 6; r++){
    for (int c = 0; c < 3; c++){
        int temp = 0;
        temp = Integer.parseInt(sc.nextLine().trim());
        tri[r][c] = temp;
        System.out.print(tri[r][c]+" ");
    }
    System.out.println();
}

This should fix it !
Note you file should have one integer per line.

Answer provided StackFlowed is correct. Just comment out "sc.nextLine()" in outer for loop. It'll make you skip one number after every row.

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