【问题标题】:Search for a line in a file that matches the given condition在文件中搜索与给定条件匹配的行
【发布时间】:2015-06-25 17:25:00
【问题描述】:

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

我想提示用户输入一个数字(例如一个密码)和一个比较符号(=、、)

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

这是我目前所拥有的:

        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);
                }
            } 

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

【问题讨论】:

  • 文本文件包含字符串和整数,用户输入其中一个整数,然后他输入一个 =、,如果有行包含例如小于什么的整数他输入,然后它打印所有这些行

标签: java file integer compare


【解决方案1】:

虽然我不确定你在问什么,但根据我对你的要求的理解,我可以为你提供以下信息。

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

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
}

【讨论】:

  • 对于 if(val > compare) 它说它不能将字符串与 int 进行比较,这是一个糟糕的二元运算符。我该如何解决?
  • @Paul 哦,是的。我忘记将 String val 转换为整数。您可以通过将 if 语句更改为 if(Integer.valueOf(val) > compare) 来做到这一点。我已经更新了我的答案。
  • 谢谢!您的代码适用于整数,唯一的问题是它也不会在行上打印字符串。它只在行上打印整数。是在 replaceAll 方法中吗?
  • @Paul 是的。该方法实际上设置了之前定义的行。如果您希望打印整行,您可以声明一个新字符串并将其设置为 line.replaceAll(...)。如果这解决了您的问题,请不要忘记将其标记为答案
  • 刚刚将您的标记为答案。我只是对这个replaceAll有点困惑。那么我会删除当前的 replaceAll 行吗?那么新人会怎么说呢?抱歉这么直接。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2015-05-03
相关资源
最近更新 更多