Click here to Skip to main content
15,359,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got a program that based on what the type of car I'm working with, it will call a set number of methods. One of the type of cars that I'm working with will go through this snippet of code:

if (infocar[0] == "E") {

        if (ElectricCar.isValidPlate(infocar[1]) == true)
        {
            int elecPower = Integer.parseInt(infocar[3]);
            double batCharge = Double.parseDouble(infocar[4]);
            if (ElectricCar.isValidelectricPower(elecPower) == true)
            {if (ElectricCar.isValidbatteryCharge(batCharge) == true){
                ElectricCar miElectricCar = new ElectricCar(infocar[1], infocar[2], elecPower, batCharge);
                electricCityCars[cochesE] = miElectricCar;
                cochesE++;}
                else{}
            }else {}
        }else{}
    } else{}


The idea is that if the inputs are correct, and object of class ElectricCar will be created and then added to the array electricCityCars[];

Then, I create another method, which will go through the array of electric cars and invoke another method:

for (int i=0; i<=25; i++) {
    EPower = electricCityCars[i].getElectricPower();
    TotalPowerElectric += EPower;
}


Problem is that on the main, Im getting NullPointerException because Im calling a null object on .getElectricPower(), but isn't the object getting created properly?
While writing this question, I noticed that I should handle the case where there are no electric cars, but atleast with the file from which I'm extracting the different car types, there is 1 electric car.

The full code if you need it is as follows :
<pre>package P3;

import java.util.Scanner; 
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

public class P3a {
 public static void main(String[] args)throws FileNotFoundException {
     String nombrefichero = args[0];
     //Atributos de varios coches
     String  plate3 = "6288LYM", manufacturer3="Ford"; int power3=110; float batteryCharge3 = 120.5F;
     String plate4 = "07451JMR", manufacturer4 = "Seat"; int power4=60; float batteryCharge4 = 10.1F;
     String plate5 = "3400JXK", manufacturer5 = "Peugeot"; int power5=70; float batteryCharge5 = 50F;
     String plate6 = "0041LDR", manufacturer6 = "Seat"; int power6 = 20; float batteryCharge6 = 10.1F;

     ElectricCar miElectricCar1 = new ElectricCar("1111KLS", "SEAT", 220, 30.5);

     ElectricCar miElectricCar2 = new ElectricCar();
     miElectricCar2.setPlate("2222LSX");
     miElectricCar2.setManufacturer("FORD");
     miElectricCar2.setElectricPower(220);
     miElectricCar2.setBatteryCharge(30.5);//COMAS

     String s1 = miElectricCar1.toText();
     String s2 = miElectricCar2.toText();	 
     System.out.println(s1);
     System.out.println(s2);


     if (ElectricCar.isValidPlate("6288LYM") == true)
	 {if (ElectricCar.isValidelectricPower(110) == true)
		 {if (ElectricCar.isValidbatteryCharge(120.5) == true)
			 {ElectricCar miElectricCar3 = new ElectricCar("6288LYM", "Ford", 110, 120.5);} //else{}
		 }//else{}
	 }//else{}
     

     if (ElectricCar.isValidPlate("07451JMR") == true)
	 {if (ElectricCar.isValidelectricPower(60) == true)
		 {if (ElectricCar.isValidbatteryCharge(10.1) == true)
			 {ElectricCar miElectricCar3 = new ElectricCar("07451JMR", "Seat", 60, 10.1);} //else{}
		 }//else {}
	 }//else{}
     

     if (ElectricCar.isValidPlate("3400JXK") == true)
	 {if (ElectricCar.isValidelectricPower(70) == true)
		 {if (ElectricCar.isValidbatteryCharge(50) == true)
			 {ElectricCar miElectricCar3 = new ElectricCar("3400JXK", "Peugeot", 70, 50);}// else{}
		 }//else {}
	 }//else{}
     

     if (ElectricCar.isValidPlate("0041LDR") == true)
	 {if (ElectricCar.isValidelectricPower(20) == true)
		 {if (ElectricCar.isValidbatteryCharge(10.1) == true)
			 {ElectricCar miElectricCar3 = new ElectricCar("0041LDR", "Seat", 20, 10.1);} //else{}
		 }//else {}
	 }//else{}
     ///////////////////////////////////////////////////////////////
     System.out.println("Hola");
     new P3a().readCityCarsFile(nombrefichero);
     int Power = new P3a().computeTotalPower();
     System.out.println(Power);
     System.out.println("Hola");
     File ficheroescritura = new File("ElectricCarsOutput.txt");
     PrintWriter pw = new PrintWriter(ficheroescritura);

     for (int l=0; l<=25; l++) {
	 electricCityCars[l].increaseBatteryChargeLevel(10);
	 pw.println(electricCityCars[l].toText());
     }
     pw.close();
     ///////////////////////////////////////////////////////////////

     
 } //FIN DEL MAIN
    //ARRAYS DE COCHES
    static ElectricCar[] electricCityCars = new ElectricCar[25];
    static CombustionCar[] combustionCityCars = new CombustionCar[25];
    static HybridCar[] hybridCityCars = new HybridCar[25];
    private static int cochesC = 0;
    private static int cochesE = 0;
    private static int cochesH = 0;
    //METODO
    
    public void readCityCarsFile (String fichero) {

	File file = new File(fichero);
	Scanner inputfichero = new Scanner(fichero);
	
	do {
	    String linea = inputfichero.nextLine();
	    if (linea.startsWith("#")) { //COMPROBAMOS SI UNA LINEA EMPIEZA POR #, SI ES EL CASO, LA SALTAMOS
		continue;
	    }
	    else {
	        
		String[] infocar = linea.split(";"); //SI NO ES UN COMENTARIO, SE DIVIDE A PARTIR DE :
		
	        if (infocar[0] == "C") {
		    
		    
		    if (CombustionCar.isValidPlate(infocar[1]) == true)
			{
			    int mecPower = Integer.parseInt(infocar[3]);
			    if (CombustionCar.isValidmechanicalPower(mecPower) == true){
				CombustionCar miCombustionCar = new CombustionCar(infocar[1], infocar[2], mecPower);
				combustionCityCars[cochesC] = miCombustionCar;
				cochesC++;} else{}
			}else{}
		} else{}
		if (infocar[0] == "E") {
		    
		    if (ElectricCar.isValidPlate(infocar[1]) == true)
			{
			    int elecPower = Integer.parseInt(infocar[3]);
			    double batCharge = Double.parseDouble(infocar[4]);
			    if (ElectricCar.isValidelectricPower(elecPower) == true)
				{if (ElectricCar.isValidbatteryCharge(batCharge) == true){
					ElectricCar miElectricCar = new ElectricCar(infocar[1], infocar[2], elecPower, batCharge);
					electricCityCars[cochesE] = miElectricCar;
					cochesE++;}
				    else{}
				}else {}
			}else{}
		} else{}
		
		
		if (infocar[0] == "H") {
		    if (HybridCar.isValidPlate(infocar[1]) == true)
			{
			    int mhpower = Integer.parseInt(infocar[3]);
			    int mepower = Integer.parseInt(infocar[4]);
			    double bathCharge = Double.parseDouble(infocar[5]);
			    if (HybridCar.isValidmechanicalPower(mhpower) == true)
				{if (HybridCar.isValidelectricPower(mepower) == true)
					{if (HybridCar.isValidbatteryCharge(bathCharge) == true){
						
						HybridCar miHybridCar = new HybridCar(infocar[1], infocar[2], mhpower, mepower, bathCharge);
						hybridCityCars[cochesH] = miHybridCar;
						cochesH++;}
					    else{}
					}else{}
				}else{}
			}else{}
		}else {}

	    }	    
	   		
	
		    
	} while(inputfichero.hasNext() == true); //SEGUIRA LEYENDO FILAS DE COCHES MIENTRAS HAYA CONTENIDO EN EL FICHERO
	
	inputfichero.close();
    }


    public static int computeTotalPower () {
	 int EPower = 0;
	 int MPower = 0;
	 int TotalPowerElectric = 0;
	 int TotalPowerMechanical = 0;
         int TotalPower = 0;
	
	for (int i=0; i<=25; i++) {
	    EPower = electricCityCars[i].getElectricPower();
	    TotalPowerElectric += EPower;
	}

	for (int i=0; i<=25; i++) {
	    MPower = combustionCityCars[i].getMechanicalPower();
	    TotalPowerMechanical += MPower;
	}

	for (int i=0; i<=25; i++) {
	    EPower = hybridCityCars[i].getElectricPower();
	    MPower = hybridCityCars[i].getMechanicalPower();
	    TotalPowerElectric += EPower;
	    TotalPowerMechanical += MPower;
	}
	TotalPower = TotalPowerElectric + TotalPowerMechanical;
	return TotalPower;
    }

}


What I have tried:

I have already tested most methods on the main, such as the "isValid" methods, and again, I've checked that there is atleast 1 electric car on the .txt.

Each array is declared as a global variable outside the main, since we were told to do that.
Posted
Updated 10-Mar-22 0:43am

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and the debugger will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
   
You are creating your sets of cars from the input of a file. You then try to access 25 entries in each array. But nowhere do you actually check that the array contains exactly 25 entries. You should use the counters cochesC, cochesE and cochesH as the maximum values for your loops.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900