JAVA 我从文本文件扫描的二维数组打印时没有第一列

标签 java multidimensional-array text-files

我正在学校的实验室工作,因此任何帮助将不胜感激,但我不希望这个问题为我解决。我在 NetBeans 中工作,我的主要目标是通过扫描文本文件中的整数来创建“二维”数组。到目前为止,我的程序运行没有错误,但我缺少数组的第一列。我的输入如下所示:

6
3
0 0 45
1 1 9
2 2 569
3 2 17
2 3 -17
5 3 9999
-1

其中 6 是行数,3 是列数,-1 是哨兵。我的输出如下所示:

0 45 
1 9 
2 569 
2 17 
3 -17 
3 9999 
End of file detected.
BUILD SUCCESSFUL (total time: 0 seconds)

如您所见,除了缺少第一列之外,所有内容都打印正确。

这是我的程序:

import java.io.*;
import java.util.Scanner;

public class Lab3
{
    public static void main(String[] arg) throws IOException
    {
        File inputFile = new File("C:\\Users\\weebaby\\Documents\\NetBeansProjects\\Lab3\\src\\input.txt");
        Scanner scan = new Scanner (inputFile);
        final int SENT = -1;
        int R=0, C=0;
        int [][] rcArray;  

        //Reads in two values R and C, providing dimensions for the rows and columns.
        R = scan.nextInt();
        C = scan.nextInt();        

        //Creates two-dimensional array of size R and C.
        rcArray = new int [R][C];   

        while (scan.nextInt() != SENT)   
                {            
                    String line = scan.nextLine();
                    String[] numbers = line.split(" ");
                    int newArray[] = new int[numbers.length];

                    for (int i = 1; i < numbers.length; i++)
                    {
                        newArray[i] = Integer.parseInt(numbers[i]);
                        System.out.print(newArray[i]+" ");                        
                    }
                    System.out.println();
                }

                System.out.println("End of file detected.");    
    }

}

显然,这里存在逻辑错误。有人可以解释一下为什么第一列不可见吗?有没有办法我只能使用我的 rcArray 或者我必须同时保留我的 rcArray 和 newArray?另外,如何让我的文件路径只读取“input.txt”,以便我的文件路径不那么长?文件“input.txt”位于我的 Lab3 src 文件夹中(与我的程序相同的文件夹),所以我想我可以使用 File inputFile = new File("input.txt");找到该文件,但我找不到。

//编辑

好的,我已经更改了这部分代码:

for (int i = 0; i < numbers[0].length(); i++)
{
  newArray[i] = Integer.parseInt(numbers[i]);                        
  if (newArray[i]==SENT)
     break; 
  System.out.print(newArray[i]+" ");                        
}
System.out.println();

运行程序(从 0 而不是 1 开始)现在给出输出:

0 
1 
2 
3 
2 
5 

这恰好是第一列。 :) 我已经取得进展了!

//编辑2

如果有人关心的话,我已经弄清楚了一切。 :) 感谢您的所有帮助和反馈。

最佳答案

既然你不希望这个问题为你解决,我会给你一个提示:

Arrays in Java是基于 0 的,而不是基于 1 的。

关于JAVA 我从文本文件扫描的二维数组打印时没有第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285120/

相关文章:

java - 更改返回类型为接口(interface)中 Object 的重写方法的返回类型 - java

python - Numpy 沿新轴重复数组

sql-server - 使用 SSIS 创建并写入文本文件

c - fscanf 检索数字信息的模式

java - 数据绑定(bind)不适用于大写字母包名称

java - gmail 回复不使用 javamail : cannot set reply

java - 在 Spring Controller 的重定向中将请求方法从 POST 更改为 GET

loops - 对于高维数组,Julia 中的数组访问循环很慢

带有 "themes"的 JavaScript 关联数组

C 文本文件到结构体、数组,然后输出