在文件中搜索与给定条件

时间:2015-06-25 17:25:00

标签: java file integer compare

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

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

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

这是我到目前为止所做的:

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

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

1 个答案:

答案 0 :(得分: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
}