在我的程序块中,我试图获取用户输入并将它与文件“PriceList3.txt”中的每一行进行比较。对于每一行,我都存储了一些字符串变量。当其中一行的某些内容与用户输入(contains方法)相同时,我使用Pattern和Matcher类来提取某些信息,并将txt文件的一行部分分配给一个变量。在我调用setPrice方法后,我试图停止阅读“PriceList3.txt”文件。当if(m.find())中的所有语句都被执行后,您是否知道如何停止读取文件?我不知道从哪里开始。停止读取某一行的文本文件java
感谢您的回复和帮助。
String regularExpr = "([\\w]+)\\s+([\\w]+)\\s+([\\d.\\d)]+)[\\D]+([\\d.\\d]+)";
Pattern pattern = Pattern.compile(regularExpr);
File inFile = new File("PriceList3.txt");
Scanner read = new Scanner(inFile);
System.out.print("Enter the name and weight of the item: ");
String item = scan.nextLine();
while(read.hasNextLine())
{
String each = read.nextLine();
if(each.contains(item))
{
Matcher m = pattern.matcher(each);
if(m.find())
{
String itemName1 = m.group(1).trim()+ " " + m.group(2);
itemName.setName(itemName1);
String weight = (m.group(3).trim());
double weight1 = Double.parseDouble(weight);
itemName.setWeight(weight1);
double itemPrice = Double.parseDouble(m.group(4).trim());
itemName.setPrice(itemPrice);
}
cashier1.addItem(itemName);
}
}
“break”将停止并退出循环。所以,如果你把它放在你的if语句的末尾,你会突破意志循环并在代码之后运行代码。 –