我正在尝试在文件中搜索 Java 语言的字符。为此,我正在使用 Scanner
扫描文件。
为了检查层次结构工作,我正在使用 System.out.print("Worked till here!");
这样我就可以检查它是否被执行。我能够执行代码直到最后阶段,但后来我发现必不可少的boolean
变量没有被改变,这是在检查是否有字符匹配的情况下的。
文件内容如下
Ok, here is some text!
Actually this file is created to test the validity of the java application
Java is my favourite programming language.
And I think I can score even more :)
Wish me luck!
但是,无论我搜索什么,它总是提示我 false
.
这是我正在使用的代码
public static void main (String[] args) throws IOException {
// Only write the output here!!!
System.out.print("Write the character to be found in the File: ");
Scanner sc = new Scanner(System.in);
String character = sc.next();
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character);
// Close the resource!
sc.close();
}
执行的方法调用,方法如下
public static void getCharacterLocation (String character) throws IOException {
System.out.println("File found...");
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
System.out.print(sc.nextLine() + "\n");
lineNumber++;
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("Something was found!");
} else {
// Nope didn't found a fuck!
System.out.println("Sorry, '" + character +
"' didn't match any character in file.");
}
sc.close();
}
不用介意变量和数组的额外使用。如果我可以获取该字符并将该值设置为 true,我将在进一步编码中使用它。
这是该程序的输出。
初始阶段
这是初始阶段。我写了Ok
在输入字段中,您可以看到 Ok
也是文件中的第一个字符。
最后阶段
这是执行后的结果。
这方面有什么帮助吗?
最佳答案
您计算行数并且不重新启动扫描仪。
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line..."); // <------
while(sc.hasNextLine()) {
添加例如
根据评论更新
sc.close();
sc = new Scanner(file);
在下一个while(sc.hasNextLine())
关于java - 这个文件扫描器代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23889251/