【问题标题】:How do I take values read from a CSV file in java in one method and use them in another method?如何以一种方法从 Java 中的 CSV 文件中读取值并在另一种方法中使用它们?
【发布时间】:2019-12-30 01:08:06
【问题描述】:

我读入了一个 CSV 文件,其中包含 2x2 矩阵的因子,现在我尝试将这些值发送到用于操作卡方检验的方法。我试图将值返回给一个名为 statResults 的类,然后在另一个调用 statResults 的类中使用它们。

public class CSVReaderJava {

    public double getComponents() throws FileNotFoundException {

        File csv = new File("Matrices.csv");    
        Scanner scnr = new Scanner(csv);    
        scnr.useDelimiter(Pattern.compile(",|$", Pattern.MULTILINE));

        int lineNumber = 1;

        scnr.nextLine();
        scnr.nextLine();
        while(scnr.hasNextLine() && lineNumber == 10){

            String targRef = scnr.next();
            double targref = Double.parseDouble(targRef);
            String targett = scnr.next();
            double target2 = Double.parseDouble(targett);
            String baseRef = scnr.next();
            double baseref = Double.parseDouble(baseRef);
            String baseTarg = scnr.next();
            double basetarget = Double.parseDouble(baseTarg);
            String fish2 = scnr.next();           
            String fishLeft = scnr.next();
            String fishRight = scnr.next();          
            String expValue = scnr.next();

            System.out.println(lineNumber + " :" +targref+" "+target2+" "+baseref+" "+
                    basetarget+" "+fish2+" "+fishLeft+" "+fishRight+" "+expValue);
            System.out.println("--------------------------");
            scnr.nextLine();
            scnr.nextLine();
            lineNumber++;   

            statResults components = new statResults();
            components.targetReference = targref;
            components.baseReference = baseref;
            components.target = target2;
            components.baseTarget = basetarget;        
            return components;
        }         
        scnr.close();      

    }   
    public statResults getStatResults() {
        return getComponents();
    }

我收到返回组件“类型不匹配:无法从 statResults 转换为 double”和 components.targetReference/others “targetReference 无法解析或不是字段”的错误

我在这里声明了字段:

public class statResults {
        public double rightTail;
        public double leftTail;
        public double twoTail;

        public double targetReference;
        public double target;
        public double baseReference;
        public double baseTarget;                   
}

想知道下一步该做什么帮助我

【问题讨论】:

    标签: java csv parsing methods field


    【解决方案1】:

    您的getComponents 方法应该返回statResults,而不是double。

    如下更改您的方法签名:

    public statResults getComponents() throws FileNotFoundException {
    
          // your code...
    
    }
    

    这应该可以解决您的问题。

    【讨论】:

    • 是的,这是正确的。但是return components; 语句也不在正确的位置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多