Search code examples
javaexceptionnullpointerexceptionprogram-entry-point

Error: Exception in thread "main" java.lang.NullPointerException


I am getting this error as a result on my code.

Here is my code:

import java.util.*;
public class car{
public static void main(String[]args) throws java.io.IOException{
Scanner v = new Scanner(System.in);

String model = new String(); 
double cost=0;

System.out.print("Enter model: ");
model = System.console().readLine();

if(model == "GL"){
    cost = 420000;
    }

if (model == "XL"){
    cost = 3398000;
    }






System.out.print("Car phone: ");
char phone = (char)System.in.read();

if(phone == 'W'){
cost = cost + 40000;
}

System.out.print("Full or installment: ");
char paid = (char)System.in.read();

if(paid == 'F'){
cost = cost - 0.15 * cost;
}

System.out.print("Cost: " + cost); 

}
}

and this is the result. An error: Enter model: Exception in thread "main" java.lang.NullPointerException at car.main(car.java:10)


Solution

  • The problem is with the following line:

    model = System.console().readLine(); 
    

    At the time you’re calling readLine(), the System.console() is null - hence why you get a NullPointerException. All you need to do is use the Scanner.nextLine() method, i.e. replacing this line with:

    model = v.nextLine();