Skip to content
Advertisement

Return string next to another inside a .txt file (JAVA)

I have a .txt file that reads for example:

AAA 1234
ZZZ 4561
LKH 9000

The idea is to create a function that receives a strinf and compares it to the first three characters, in this case, AAA, ZZZ or LKH, and if it is equal, it returns the numeric value, but my comparison isn’t working as intended, because the comparison doesn’t seem to be working as expected. Here’s my code so far:

public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch(NumberFormatException e){
            return false;
        }
    }

public static PrintStream returnIntNext(){
Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("sample.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    while (sc2.hasNextLine()) {
        Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            if ("LKH".equals(s)){
                if (isNumeric(s)){
                    System.out.println(s);}}
            else{System.out.println("if line not working");}
        }}
    return null;
}

Any clues on what I’m doing wrong?

Advertisement

Answer

The same string is checked for “LKH” and is expected to be numeric.

if ("LKH".equals(s)){
   if (isNumeric(s)){
       System.out.println(s);
   }
}

After checking for “LKH”, do another s2.next() to get the next string, which should be the number you want.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement