gpt4 book ai didi

java - 在文件中搜索与给定条件匹配的行

转载 作者:行者123 更新时间:2023-12-01 11:22:45 25 4
gpt4 key购买 nike

我正在为一项作业编写一个程序,用户可以在其中搜索文本文件的内容。文本文件包含带有文本和数字的行。

我想提示用户输入数字(例如 PIN 码)和比较符号(=、<、>、)

我想根据给定的比较符号获取并打印文件行中与给定数字匹配的数字。

这是我到目前为止所拥有的:

        System.out.print("Enter integer: ");
String Value = input.next();

System.out.print("Enter type (=, <, >): ");
String Type = input.next();

while (file.hasNextLine())
{
String lines = file.nextLine();
if(lines.contains(Value))
{
if (compareType.equals(">"))
{
System.out.println(lines);
}
}

感谢您提供的任何帮助。谢谢。

最佳答案

虽然我不确定您在问什么,但根据我对您请求的理解,我可以为您提供以下内容。

您开始正确地从用户那里获取所需的值。

System.out.print("Enter integer: ");
String val = input.next();

System.out.print("Enter type (=, <, >): ");
String operator = input.next();

while(file.hasNextLine()){
String line = file.nextLine();
if(operator.equals("=") && line.contains(val)){ //check if operator is equals and if line contains entered value
System.out.println(line);//if so, write the current line to the console.
}else if(operator.equals(">")){//check if operator is greater than
String integersInLine = line.replaceAll("[^0-9]+", " ");//we now set this to a new String variable. This variable does not affect the 'line' so the output will be the entire line.
String[] strInts = integersInLine.trim().split(" "))); //get all integers in current line
for(int i = 0; i < strInts.length; i++){//loop through all integers on the line and check if any of them fit the operator
int compare = Integer.valueOf(strInts[i]);
if(Integer.valueOf(val) > compare)System.out.println(line);//if the 'val' entered by the user is greater than the first integer in the line, print the line out to the console.
break;//exit for loop to prevent the same line being written twice.
}
}//im sure you can use this code to implement the '<' operator also
}

关于java - 在文件中搜索与给定条件匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com