我的代码是从 .txt 中读取行并解析这些输入。
输入是这种形式<operation> <category> <name> <price> <quantity> <weight> <optional field1> <optional field2>
电子产品有 2 个选项字段是否易碎 (F/NF) 和要运送到的状态,杂货有 1 个可选字段易腐烂 (P/NP)。这是行输入的一些示例
insert clothing shirt 20.50 1 1
insert electronics PS3 300 1 5.2 F NM
insert groceries cabbage 2.00 5 1 NP
我正在考虑编写一种legalLine()
方法来处理输入中的错误
class sampleClass{
public static void isLegalLine(String lineInput){
Scanner s = new Scanner(lineInput);
String operation = null;
String category = null;
String name = null;
float price = 0;
int quantity = 0;
float weight = 0;
String opt1 = null;
String opt2 = null;
try{
operation = s.next();
category = s.next();
name = s.next();
price = Float.parseFloat(s.next());
quantity = Integer.parseInt(s.next());
weight = Float.parseFloat(s.next());
if (!operation.equalsIgnoreCase("insert")
&& !operation.equalsIgnoreCase("search")
&& !operation.equalsIgnoreCase("delete")
&& !operation.equalsIgnoreCase("update")
&& !operation.equalsIgnoreCase("print")) {
System.out.println("invalid operation");
}
// more validations for variables category, name, price, quantity, weight goes here
if(category.equalsIgnoreCase("electronics")){
try{
opt1 = s.next();
opt1 = s.next();
}catch(Exception e){
}
}else if(category.equalsIgnoreCase("groceries")){
opt1 = s.next();
}
}catch (Exception e){
//general catch for now
e.getMessage();
}
}
public static void main(String[] args)
{
FileReader freader = new FileReader(args[0]);
BufferedReader bfrReader = new BufferedReader(freader);
isLegalLine(bfrReader.readLine());
//program does calculation for total price of input
}
你看......我已经经历了将每个令牌设置为其各自变量的所有麻烦isLegalLine()
,我怎样才能将这些信息传递回main()
?这是处理输入行错误的好设计吗?