简体   繁体   中英

Find a word and return specific value of the word

I have a file with this content:

1.10.100.1        1000.0
1.10.100.2        2000.0
1.10.100.3        2000.0
1.10.500.4        1000.0

i wrote the function that find the specific string in the file:

public double searchInBalance(String depositNumber) {
    try {
        String[] words = null;
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String string;
        String inputBalanceToFind = depositNumber;
        while ((string = bufferedReader.readLine()) != null) {
            words = string.split("        ");
            for (String word : words) {
                if (word.equals(inputBalanceToFind)) {
                    System.out.println("string :" + string);
                }
            }
        }
        fileReader.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error in searchInBalance");
    }
    return 1;
}

i want to make a function that when find the left value of the file return the right value(the double value) back but have no idea how to do that please help me

  public double searchInBalance(String depositNumber){

        try {
            String[] words = null;
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String string;
            String inputBalanceToFind = depositNumber;
            while ((string = bufferedReader.readLine()) != null) {
                words = string.split("        ");

                for (int i = 1; i < words.length; i += 2) {
                    if (words[i].equals(inputBalanceToFind)) {
                       System.out.println(words[i]+" - "+words[i - 1]);
                    }
                }

            }
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error in searchInBalance");
        }
    }

Just make a for loop with a counter to work with the indexes of the Array. But this is not a good programming style and you should try to improve your solution:D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM