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