【问题标题】:Java 2d Array unable to edit value and properly return element back null valuesJava 2d 数组无法编辑值并正确返回元素返回空值
【发布时间】:2016-05-15 14:38:59
【问题描述】:

我对 java 语言的了解非常新。我的大部分知识来自谷歌搜索如何做事。我一直在研究一个使用 switch 语句的 Java 控制台程序。整个程序使用一个 String [20][5] 数组。我已经编写了代码,现在可以添加条目、将数组保存到文件、将文件中的条目加载到数组中。

现在的问题是编辑和删除条目。我能够将值返回为 null,但它看起来像这样 [[null], [null, null, null, null, null]。

我希望值返回 [null, null, null, null, null], [null, null, null, null, null]。

Edit 条目出于某些原因返回 java.lang.ArrayIndexOutOfBoundsException:1 。

有人能指出我的错误吗?数组也是全局声明的。

public static String[][] rem(){
 Scanner input = new Scanner(System.in);
 int x,y=0;
 //for(int i=0;i<array.length;i++){
        //if(array[i][0]!=null){
            System.out.println(Arrays.deepToString(array));//}
        //}
 System.out.println("Which entry would you like to remove? "
         + "\n" + "Enter number 0 - 20");
 x = input.nextInt();
 array[x][y]=null;
 return array;}


public static String[][] edit(){
 Scanner input = new Scanner(System.in);
 String k;
 int j;
 int g;
// for(int i=0;i<array.length;i++){
        //if(array[i][0]!=null){
            //System.out.println(Arrays.deepToString(array));}
        //}
 System.out.println("Which entry would you like to edit? "
         + "\n" + "Enter number 0 - 20");
 j = input.nextInt();
 System.out.println("What would you like to edit? "
         +"\n" + "Enter number 0 - 5");
 g = input.nextInt();
 System.out.println("You are now editing.");
 k = input.next();
 array[j][g] = k;
 return array;}

更新

我想我解决了我的问题。该数组正确编辑我手动输入的值。当我将数据加载到数组中时会导致问题,因为当它加载数据时,它会以字符串 [] 的形式加载。我需要一个将数据加载为 String[][] 或数组数组的代码。

public static String[][] load()throws FileNotFoundException, IOException{
  menu();
  copyFile();
  String file = ("c:/temp/Address.txt");
    Scanner scan = new Scanner(new FileReader(file));
    // initialises the scanner to read the file file

    //String[][] entries = new String[100][3];
    // creates a 2d array with 100 rows and 3 columns.
    //int i = 0;
    while(scan.hasNextLine()){
        array[i][i] = scan.next().split("," , "\t");
        i++;
    }
    //loops through the file and splits on a tab

    //for (int row = 0; row < array.length; row++) {
       // for (int col = 0; col < array[0].length; col++) {
           // if(array[row][col] != null){
               // System.out.print(array[row][0] );
           // }
       // }
       // if(array[row][0] != null){
           // System.out.print("\n");
        //}
   // }
    //prints the contents of the array that are not "null"
    selectMenu();
    return array;}

更新 2

我找到了解决加载数据问题的解决方案。解决方法很简单!我将代码留在这里以供参考。不过,所有的代码都可以使用一些美化。

public static String[][] load()throws FileNotFoundException, IOException{
  menu();
  copyFile();
  String file = ("c:/temp/Address.txt");
    Scanner scan = new Scanner(new FileReader(file));
    FileReader fr = new FileReader("c:/temp/Address.txt");
    BufferedReader br = new BufferedReader(fr);

    //int j=0;
    //int lineNo = 0;
     //String line = br.readLine();
     //while(line!=null)
     //{  
        //for(int i = 0; i < 5; i++)
        //{
           //array[lineNo][i] = line.substring(i,4);  
        //}
       // lineNo++;
        //line = br.readLine();  // This is what was missing!
     //}     
    //while(scan.hasNextLine()){
    //while(scan.hasNext()){
        //for(j=0;j<5;j++){
    for(int i = 0; i < 20; ++i){
        for(int j = 0; j < 5; ++j)
        {
            if(scan.hasNext())
            {
    array[i][j] = scan.next();
        //i++;
        //j++;
                }
    //i++;
            }
        }

    selectMenu();
    return array;}

更新 3

所以在弄清楚如何使用分隔符之后,它给了我一个奇怪的问题。它在列的末尾添加 return。 [空,空,空,空,空返回]。我使用 ",|\n" 作为分隔符。有没有更好的方法?更新:添加了 .trim();解决负载的最终问题。现在它在目前的工作中得到了完善。不过,我敢肯定,可能会有不那么原始的方法。

    public static String[][] load()throws FileNotFoundException, IOException{
   copyFile();
 //delimiter removes the comma or return to the next line. "\n" new line
   Scanner scan = new Scanner(new FileReader(file)).useDelimiter(",|\n"); 
    for(int i = 0; i < 20; ++i){
        for(int j = 0; j < 5; ++j){
                if(scan.hasNext())
                array[i][j] = scan.next().replace(",", "").trim();
            }
        }
    System.out.println("File loaded successfully!!");
    scan.close();
    return array;}

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    这是一个错误,非常微妙的错误:

    虽然您有 20 行和 5 列,但数组使用基于 0 的索引(从 0 开始计数而不是 1)。 用手指从 0 到 5 数,您会看到实际上有 6 个数字而不是 5,这会导致您的 OutOfBoundsException,因为您没有第 6 个元素。 因此,要访问您的行和列,范围应介于: 0 - 19(列)和 0 - 4(行)

    或者

    1 - 20(对于列)和 1 - 5(对于行),然后从扫描仪输入中减去 1,因为记住数组使用基于 0 的索引。

    文件读取更新:

    public static String[][] load() {
    
       try{
          FileReader fr = new FileReader("c:/temp/Address.txt");
          BufferedReader bf = new BufferedReader(fr);
          String presentLine = "";
          for(int i = 0; i < 20; i++) {
            for(int j = 0; i < 5; j++) {
                 if ((presentLine = bf.readLine()) != null) {
                       array[i][j] = presentLine;
                 }
            }
          }
       } catch(Exception e) {
          System.out.println(e);
       }
    
       selectMenu();
       return array;
    }
    

    虽然这可以做得更好,但没关系。 您可以将 20 和 5 分别存储为称为行和列的静态变量,以避免使用硬编码数字。

    【讨论】:

    • 感谢您的回答。不过,我仍然有一个问题,即 remove 不会在它的 5 列中正确返回 null 。假设我输入第 0 行和循环第 0-4 列,它会给我一个 OutOfBoundsException(for(y=0;y
    • 如果我手动输入数据就可以了。现在我需要想出一种新方法来正确地将文本文件加载到数组中。
    • 代码是否也能够将元素组合和分离到适当的列中?当它加载类似“led 铅笔”之类的内容时,我似乎忽略了它,它加载为 [led,pencil,null,null,null]。什么时候应该是[led pencil, null, null, null, null]。
    • 取决于您是否使用 bufferedReader 的扫描仪,如果您使用的是 bufferedReader,readLIne() 会读取整行并将其插入到数组中,但由于您使用的是扫描仪而不是 hasNext( ) 你可以使用 hasNextLine()
    • 我之前使用过 hasNextLine() 但如果有超过 1 个条目“led Pencil 100 仓库 3”,它将全部放在第一行。我之前尝试过使用 useDelimiter() ,但我不知道如何正确读取它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多