我正在编写一些代码以从文本键盘读取静态库存编号。我运行它来查看出了什么问题,并且我似乎无法修复此无法找到符号错误的问题。

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

public class StockMarket
{
    public static void main(String[] args) throws IOException
    {

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter the filename: ");
        String filename = keyboard.nextLine();

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);

        while (inputFile.hasNext())
        {
            checkValidity();
        }

        inputFile.close();

    }

    public static boolean checkValidity()
    {

    String line = inputFile.nextLine();
    double numberOfShares = inputFile.nextDouble();
    double buyPricePerShare = inputFile.nextDouble();
    double buyComissionRate = inputFile.nextDouble();
    double sellPricePerShare = inputFile.nextDouble();
    double sellComissionRate = inputFile.nextDouble();

    }

}

最佳答案

您的checkValidity()方法遇到的问题很少,如下所述:

(1)您的Scanner对象范围仅存在于main方法内部,因此请将该对象传递给checkValidity方法

(2)验证checkValidity方法中的输入

(3)您的checkValidity方法具有return类型的boolean,因此您需要从中return一个boolean值,即,如果验证成功,则返回true或如果验证失败,则返回false

您使用内联注释引用以下代码:

public static boolean checkValidity(Scanner inputFile) {
        String line = inputFile.nextLine();
        double numberOfShares = inputFile.nextDouble();
        double buyPricePerShare = inputFile.nextDouble();
        double buyComissionRate = inputFile.nextDouble();
        double sellPricePerShare = inputFile.nextDouble();
        double sellComissionRate = inputFile.nextDouble();
        boolean validationSuccess = false;
        //validate your inputs
        // If validations are successful  then set validationSuccess = true;
        return validationSuccess;//return boolean
    }


另外,如下所示从scanner传递main()对象:

while (inputFile.hasNext()) {
     checkValidity(inputFile);//pass scanner object
}

09-11 18:37