Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading