【问题标题】:Returning an int array in Java在 Java 中返回一个 int 数组
【发布时间】:2021-11-01 11:29:29
【问题描述】:

所以我需要一个返回文本文档数组的脚本。文件全是数字。每次我尝试运行它时,我都会收到此消息“此方法必须返回 int [] 类型的结果”,这是在检查器部分下。我正在尝试将它返回到另一个类,以便我可以将数组用于 if 语句。谁能帮我解决这个问题?

import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
public static int[] checker(){
    try {
        File myObj = new File("Tracker.txt");
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            String[] moreData = data.split("\n");
            int day = Integer.parseInt(moreData[0]);
            int Posts = Integer.parseInt(moreData[1]);
            return new int[] {day, Posts};
        }
        
        myReader.close();
    } catch (FileNotFoundException e) {
        return new int[] {0, 0};
    }
    }

}

预期结果是:{0, 40}

【问题讨论】:

  • 请告诉我们您的方法的预期输出应该是什么。从您的代码中并不清楚,它充满了问题。
  • 抱歉,我是 java 新手,还在尝试弄明白。
  • 我添加了预期的结果
  • 所有可能的返回路径都必须返回int[]。在您的代码中,myReader.hasNextLine() 可能会返回 false。在这种情况下,由于既没有输入while 循环也没有输入catch 块,因此无法到达return 语句。
  • “文件全是数字” - 以什么方式?他们在不同的行吗?用空格隔开?除了修复明显的编译器错误之外,很难为问题提出准确的解决方案

标签: java arrays integer


【解决方案1】:

编译器抱怨是因为它认为有一个可能的退出路径会跳过所有其他 return 语句。如果hasNextLine 在第一次交互时返回false 会怎样?

在这种情况下,您应该将catch 子句中的return 移到方法的末尾

import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {

    public static int[] checker() {
        File myObj = new File("Tracker.txt");
        // This will ensure that the Scanner is closed when
        // you exit from the loop early
        try (Scanner myReader = new Scanner(myObj)) {
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                // Why?  You just read the line, there
                // are no more lines in this text?!
                String[] moreData = data.split("\n");
                int day = Integer.parseInt(moreData[0]);
                int Posts = Integer.parseInt(moreData[1]);
                // Why?? Are there only two values in the
                // whole file?!  Then you should use if (...) instead of while (...)
                return new int[]{day, Posts};
            }
        } catch (FileNotFoundException e) {
            // You should at least print an error   
        }
        return new int[]{0, 0};
    }

}

查看The try-with-resources Statement 了解更多关于try (Scanner myReader = new Scanner(myObj)) { 正在做什么的信息

它们的数字由换行符分隔,如下所示:0 40 30

所以,更好的解决方案可能看起来像......

public static int[] checker() {
    File myObj = new File("Tracker.txt");
    List<Integer> values = new ArrayList<Integer>(128);
    try (Scanner myReader = new Scanner(myObj)) {
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            int value = Integer.parseInt(data);
            values.add(value);
        }
    } catch (FileNotFoundException e) {
        System.out.println("Something went wrong");
    }
    return values.stream().mapToInt(Integer::intValue).toArray();
}

使用这个数组的问题在于你不知道有多少行(或元素),所以你需要更动态的东西,比如List,你可以不断添加新元素,而无需知道您需要预先存储多少。

这有点“高级”,但一般来说,在大多数情况下,我会考虑在数组上使用List,但那是我,我很懒。

预期结果是:{0, 40}

如果你只想要固定数量的元素,那么计算你已经阅读的行数,当你到达它时提前退出

public static int[] checker() {
    File myObj = new File("Tracker.txt");
    try (Scanner myReader = new Scanner(myObj)) {
        int line = 0;
        int[] values = new int[2];
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            int value = Integer.parseInt(data);
            values[line] = value;
            line += 1;
            if (line > 1) {
                // Early exit
                break;
            }
        }
        return values;
    } catch (FileNotFoundException e) {
        System.out.println("Something went wrong");
    }
    return new int[] { 0, 0 };
}

【讨论】:

  • ...但是这种方法没有意义,因为while 循环将在第一次迭代后返回,这几乎肯定不是 OP 想要的逻辑。
  • @TimBiegeleisen 因为我只被要求修复编译器错误 - 这就是我所做的。我并没有试图推理 OP 实际上试图做什么。如果文件只包含一行文本,那么if(myReader.hasNextLine()) 会更合适——但他们为什么要尝试用换行符分割刚刚读取的行?!很高兴看到文件的预期数据结构:P
  • @TimBiegeleisen 我很感激。就像我说我是 Java 新手,所以我只是在摸索。但是,如果您有任何反馈,我很乐意??
  • @AaronCloud 好吧,除了修复你的编译器错误,我们真的无法修复逻辑,因为我们没有足够的上下文。例如,您从文件中读取了一行文本,然后尝试在新的行标记上拆分文本……但这不起作用,因为您只读取了该行文本,不会有任何其他的里面的线条。该文件是否包含单行?它是否包含多行?每行是否仅包含多个数字中的一个?如果有,如何划分?
  • @MadProgrammer 您的回答确实解决了 +1 提出的确切问题。只是评论说最好的答案是给出一个完全可行的方法。
猜你喜欢
  • 2020-11-02
  • 2021-03-29
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
相关资源
最近更新 更多