[英]Java How can I display and search the same value in a txt file so all the records are scanned and displayed if value is in the record
Here is my quest, I have the same value in records in a text file.这是我的任务,我在文本文件中的记录中具有相同的值。 But I only get to find the first one and to display the first one.
但我只能找到第一个并显示第一个。 How can I find all the record with that value and display them.
如何找到具有该值的所有记录并显示它们。 Here is the code,
这是代码,
package projectsby;
import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Find {
private static Scanner o;
public void openFile(){
try{
o = new Scanner(new File("/Users/e.h.j.hofman/NetBeansProjects/Projectsby/src/projectsby/Projects.txt"));
}
catch(Exception e) {
System.out.println("Could not find file");
}}
/**
*
* @param searchTerm
* @param filepath
*/
public void readEntries(String searchTerm, String filepath){
boolean found = false;
String Project = "";
String omschrijving = "";
String BU= "";
String afdeling = "";
try
{
o = new Scanner(new File(filepath));
//o.useDelimiter("[ \n]");
while(o.hasNext()
//&& !found )
{
Project = o.next();
omschrijving = o.next();
BU = o.next();
afdeling = o.next();
if(Project.equalsIgnoreCase(searchTerm))
{
found = true; }
}
if (found)
{
Here i suspect it will help when there is some kind of while loop.在这里,我怀疑当有某种 while 循环时它会有所帮助。
JOptionPane.showMessageDialog
(null,"Project: " + Project + " " +omschrijving + "\nBU: "
+ BU + "\nAfdeling: " +afdeling);
} else {
JOptionPane.showMessageDialog(null,"Project not found");
}}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Error");
}}
public void closeFile(){
o.close();
}}
It is a little hard to tell from your code formatting but the block of code in the "if (found)" statement will only be executed at the end of the file since it is outside the while loop.从您的代码格式中很难分辨,但“if (found)”语句中的代码块只会在文件末尾执行,因为它位于 while 循环之外。 Maybe that code should be moved to the "if(Project.equalsIgnoreCase(searchTerm))" statement instead.
也许应该将该代码移至“if(Project.equalsIgnoreCase(searchTerm))”语句。 Then it will execute on every record in the file, if the searchTerm is found.
如果找到了 searchTerm,它将在文件中的每条记录上执行。
Then there is no reason for the "found" boolean.那么就没有理由“找到”boolean。
while (o.hasNext()) {
...
if(Project.equalsIgnoreCase(searchTerm)) {
JOptionPane.showMessageDialog ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.