javanullnumberformatexception

Finding specific value in a list in java using a scanning loop: returns numberformat exception


I am trying to find a specific string in a text file. Here is what I have using [Java] Lists:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class constantb {
    static String filePath = "C:myiflepath";

    public static Double findDouble(String name) throws IOException{
        String value;
        Scanner constScanner = new Scanner(filePath);
        List<String> list=new ArrayList<>();
        while(constScanner.hasNextLine()){
            list.add(constScanner.nextLine()); 
        }
        value = list.get(list.indexOf(name)+1);
        System.out.println(value);
        constScanner.close();
        return Double.parseDouble(value);
    }
}

When I run this I get a NumberFormatException problem. In the text file it searches for a name and right below that name in the file is what I want to return as a double. Here is the text file:

help please:
double hi
9

I have tried removing the list part of the file:

import java.util.Scanner;

public class constantc{

    static String filePath = "C:myfilepath";

    public static Double findDouble(String name){
        Scanner scanner = new Scanner(filePath);
        String value = scanner.nextLine();
        while(scanner.hasNextLine()){
            value = scanner.nextLine();
            if(name == scanner.nextLine()){
                scanner.nextLine();
                value = scanner.nextLine();
                break;
            }else{
                scanner.nextLine();
            }
        }
        scanner.close();
        return Double.parseDouble(value);
    }
}

That did not work because I got the same error.


Solution

  • You aren't scanning the file, you are scanning the string literal "C:myiflepath". You need to create a file handle and scan that. Make a minor change to your first code sample as follows:

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class constantb {
        static String filePath = "C:myiflepath";
    public static Double findDouble(String name) throws IOException{
        String value;
        File file = new File(filePath); // added 
        Scanner constScanner = new Scanner(file); // changed
        List<String> list=new ArrayList<>();
        while(constScanner.hasNextLine()){
            list.add(constScanner.nextLine()); 
        }
        value = list.get(list.indexOf(name)+1);
        System.out.println(value);
        constScanner.close();
        return Double.parseDouble(value);
    }
    

    }

    Running your code in debug with a breakpoint at the start and stepping though and inspecting values would have allowed you to solve this easily.