如何在文件中查找特定系列的输入并打印结果。

huangapple go评论84阅读模式
英文:

How to find a specific series of inputs in a file and print out results

问题

我正在尝试创建一种方法,使我能够在不必浏览所有内容的情况下搜索特定人的另一项测试结果。它接受输入,例如需要查找的“学生”的姓名、年龄和性别,然后应该找到确切的学生并在其下打印结果。

我已经设置了文件,以便当有人参加测试时,他们的结果会以以下方式打印出来:

姓名
年龄
性别
结果

我希望我的代码能够查找输入的姓名,然后查看姓名下面的年龄是否匹配输入,然后查看下面的性别是否匹配输入。如果所有这些都正确,它应该打印出结果。

//这些部分要求输入姓名、年龄和性别

Scanner enterName = new Scanner(System.in);
System.out.println("请在下方输入学生的全名。");
var stuName = enterName.nextLine();

Scanner enterAge = new Scanner(System.in);
System.out.println("请在下方输入学生的年龄。");
var stuAge = enterAge.nextInt();

Scanner enterGender = new Scanner(System.in);
System.out.println("请在下方输入学生的性别(Female或Male)。");
var stuGender = enterGender.nextLine();

//这些部分搜索信息
Scanner usersName = new Scanner(new File("Example.txt"));
Scanner usersAge = new Scanner(new File("Example.txt"));
Scanner usersGender = new Scanner(new File("Example.txt"));
Scanner usersScore = new Scanner(new File("Example.txt"));
var searchName = usersName.nextLine();

//这里应该搜索信息并在找到时返回true
try {
    while (usersName.hasNextLine()) {
        searchName = usersName.nextLine();
        if (searchName.equals(stuName)) {
            break;
        }
    }
} catch (Exception e) {
    if (!searchName.equals(stuName)) {
        System.out.println("学生未找到");
    }
}

var searchAge = usersAge.nextLine();
if (!searchAge.equals(Integer.toString(stuAge))) {
    System.out.println("学生未找到");
    System.exit(1);
}
var searchGen = usersGender.nextLine();
if (!searchGen.equals(stuGender)) {
    System.out.println("学生未找到");
    System.exit(1);
}
if (searchName.equals(stuName) && searchAge.equals(Integer.toString(stuAge)) && searchGen.equals(stuGender)) {
    var searchScore = usersScore.nextDouble();
    System.out.println(stuName + "的分数是:" + searchScore);
    System.exit(1);
} else {
    System.out.println("学生未找到");
    System.exit(1);
}

在某个地方可能会出现问题,它总是打印“学生未找到”,即使我知道那些特定的结果在文件中。

示例文件

Test
1
Female
93.0%
Test
2
Female
97.0%
Test
3
Female
100.0%
英文:

I'm trying to create something that's basically a way for me to search for a certain persons results on another test without having to scroll through everything. It takes inputs, such as the name, age, and gender of whatever "student" I need to find, then it's supposed to find that exact student and print the results underneath.

I have the file set up so that when someone takes the test, their results are printed like so:

Name
Age
Gender
Results

I want my code to find the name that's inputted, then see if the age underneath the name matches the input, then see if the gender underneath that matches the input. If all of these are correct, it should print out the results.

                    //These ask for the name, age, and gender
Scanner enterName = new Scanner(System.in);
System.out.println("Please enter Student's full name below.");
var stuName = enterName.nextLine();
Scanner enterAge = new Scanner(System.in);
System.out.println("Please enter Student's age below.");
var stuAge = enterAge.nextInt();
Scanner enterGender = new Scanner(System.in);
System.out.println("Please enter Student's gender below (Female or Male).");
var stuGender = enterGender.nextLine();
//These scanners search for the information
Scanner usersName = new Scanner(new File("Example.txt"));
Scanner usersAge = new Scanner(new File("Example.txt"));
Scanner usersGender = new Scanner(new File("Example.txt"));
Scanner usersScore = new Scanner(new File("Example.txt"));
var searchName = usersName.nextLine();
//This shoulder search for the information and come back true if it's found
try {
while (usersName.hasNextLine()) {
searchName = usersName.nextLine();
if (searchName.equals(stuName)) {
break;
}
}
} catch (Exception e) {
if (!usersName.equals(stuName)) {
System.out.println("Student not found");
}
}
var searchAge = usersName.nextLine();
if(!searchAge.equals(stuAge)) {
System.out.println("Student not found");
System.exit(1);
}
var searchGen = usersGender.nextLine();
if(!searchGen.equals(stuGender)) {
System.out.println("Student not found");
System.exit(1);
}
if(searchName.equals(stuName) && usersAge.equals (stuAge) && usersGender.equals(stuGender)) {
var searchScore = usersScore.nextDouble();
System.out.println("The student " + stuName + "'s score was: " + searchScore);
System.exit(1);
} else {
System.out.println("Student not found");
System.exit(1);
}

Somewhere along the way it gets lost, and it always prints "Student not found", even when I know those particular results are in the file.

Sample File

Test
1
Female
93.0%
Test
2
Female
97.0%
Test
3
Female
100.0%

答案1

得分: 1

不需要多个扫描器来获取用户输入。您可以重复使用一个。对于在文件中搜索,您只需要一个扫描器。除此之外,您的文件似乎格式良好,所以您可以使用Scanner.findAll方法,并传递一个可以从用户输入构建的模式。类似下面的内容应该可以帮助您入门。注意:此示例没有错误处理,也没有不区分大小写的搜索。您可以自行改进这个。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Example {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner userInput = new Scanner(System.in);

        System.out.println("Please enter Student's full name below.");
        var stuName = userInput.nextLine();

        System.out.println("Please enter Student's age below.");
        var stuAge = userInput.nextInt();
        userInput.nextLine();   // 这不是疏忽,而是有意的,必要以能够读取下一个输入。

        System.out.println("Please enter Student's gender below (Female or Male).");
        var stuGender = userInput.nextLine();

        Scanner fileContent = new Scanner(new File("Example.txt"));
        // 从用户输入构造模式并正则表达式匹配百分比
        Pattern pattern = Pattern.compile(stuName + "\n" + stuAge + "\n" + stuGender + "\n" + "\\d+(?:\\.\\d+)?%");
        // 使用findAll方法并返回第一个匹配(如果存在)
        fileContent.findAll(pattern)
                   .map(MatchResult::group)
                   .findFirst()
                   .ifPresentOrElse(
                           (value) -> System.out.println("Found matching result: \n" + value),
                           ()      -> System.out.println("No matching result found"));
    }
}

编辑:

"什么是\\n\\\\d+(?:\\\\.\\\\d+)?%,它与模式有什么关系?

我将换行符与正则表达式分开,以减少混淆,并将其更改为:

"\n" + "\\d+(?:\\.\\d+)?%"

\\d+(?:\\.\\d+)?% 部分是一个用于匹配百分比的正则表达式。

  • \\d+ 匹配一个或多个数字
  • (?:\\.\\d+)? 可选地跟随一个点和一个点之后的一个或多个数字
  • % 匹配百分号字符

因此,可能的匹配可能如下,其中 x 是任意数字:

  • x% 例如 7%
  • xx% 例如 27%
  • xx.x% 例如 97.4%
  • xx.xx% 例如 84.32%
英文:

You don't need multiple scanners to get the user input. You can reuse one. The same applies for searching in the file, you only need one scanner. Apart from that, your file seems to be well formed, so you can use the Scanner.findAll method and pass a pattern that you can construct from the user's input. Something like below should get you started. Note: the example has no error handling, and also no case insensitive search. You can improve this yourself

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter Student's full name below.");
var stuName = userInput.nextLine();
System.out.println("Please enter Student's age below.");
var stuAge = userInput.nextInt();
userInput.nextLine();   //this is not an oversight but intentional and necessary to be able to read the next input.
System.out.println("Please enter Student's gender below (Female or Male).");
var stuGender = userInput.nextLine();
Scanner fileContent = new Scanner(new File("Example.txt"));
//construct pattern from user input and regex for percentage
Pattern pattern = Pattern.compile(stuName + "\n" + stuAge + "\n" + stuGender + "\n" + "\\d+(?:\\.\\d+)?%");
//use findAll method and return first match if present
fileContent.findAll(pattern)
.map(MatchResult::group)
.findFirst()
.ifPresentOrElse(
(value) -> System.out.println("Found matching result: \n" + value),
()      -> System.out.println("No matching result found"));
}
}

Edit:

> What is "\n\\d+(?:\\.\\d+)?%" and how does it relate to the pattern?

I have separeted the new line char from the regex, to reduce confusion and chnged it to :

`"\n" + "\\d+(?:\\.\\d+)?%"` 

The \\d+(?:\\.\\d+)?% part is a regex that matches percentage for marks.

  • \\d+ match one or more digits
  • (?:\\.\\d+)? optionaly followed by a dot and one or more digits after the dot
  • % match the percent character

So, possible matches could look like, where x is is any digit

  • x% ex. 7%
  • xx% ex. 27%
  • xx.x% ex. 97.4%
  • xx.xx% ex. 84.32%

``

huangapple
  • 本文由 发表于 2023年8月4日 01:19:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定