Click here to Skip to main content
15,891,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.

I have declared a LinkedHashMap like this:
LinkedHashMap <String, Car> cityCars = new LinkedHashMap <String, Car>();
where the string is going to be the plate of a car, while Car is going to be the actual Car (plate included).

In one of my methods, Im trying to add an element to the LinkedHashMap through the put(K key, V value) method:
cityCars.put(infocar[1], new CombustionCar(infocar[1], infocar[2], mecPower));
where infocar[] and mecPower are values taken from a file that Im reading, and CombustionCar extends Car.

The problem is that when I try to access these previously added elements in any other method, it turns out that the Map is empty, for example, on this method:

public int computeTotalPower () {
	 int Power = 0;
         int TotalPower = 0;
	 ArrayList <Car> temp = new ArrayList<Car>(cityCars.values());
	 System.out.println(temp.get(1).toString());
	 Car[] arrayCityCars = temp.toArray(new Car[cityCars.size()]);
	 for (int i=0; i<cityCars.size(); i++) { //SUMAMOS EL VALOR TOTAL DE POTENCIA DE CADA TIPO DE COCHE
	     Power = arrayCityCars[i].getTotalPower();
	     TotalPower += Power;
	 }
	 return TotalPower;
    }


What I have tried:

I have made sure that I was reading the lines from the file correctly right before adding the Car element to the HashMap, and it was printing the correct information, so it can't be a problem of not reading the file properly, specially since this is a modification of a previous code that I had where I used an ArrayList instead of a LinkedHashMap.

On the method where Im trying to access the cityCars elements I also tried adding the line
System.out.println(temp.get(1).toString());
to make sure once again that the Map was empty, and this gave me a NullPointerException, so the Map is indeed empty.

Here is the full code of this one class. Every other class that I use here works just fine, since Ive used them before.

package P6b;

import java.util.Scanner; 
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;

public class CarDB {

    LinkedHashMap <String, Car> cityCars = new LinkedHashMap <String, Car>();

    private int coches = 0;
    private int cochesEH = 0;
    
    public void readCityCarsFile (String fichero)throws FileNotFoundException {
	Scanner input = new Scanner (System.in);
	File file = new File(fichero);
	Scanner inputfichero = new Scanner(file);
	
	
	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].equals("C") == true) { //EN FUNCION DEL TIPO DE COCHE QUE ESTEAMOS LEYENDO, REALIZAREMOS UNA SERIE DE PRUEBAS SOBRE SUS ATRIBUTOS ANTES DE CREAR EL OBJETO
		    
		    
		    if (CombustionCar.isValidPlate(infocar[1]) == true)
			{
			    int mecPower = Integer.parseInt(infocar[3]);
			    if (CombustionCar.isValidmechanicalPower(mecPower) == true){
				cityCars.put(infocar[1], new CombustionCar(infocar[1], infocar[2], mecPower)); 
				coches++;} 
			}
		} 
		
		if (infocar[0].equals("E") == true ) {
		    
		    if (ElectricCar.isValidPlate(infocar[1]) == true)
			{
			    int elecPower = Integer.parseInt(infocar[3]);
			    infocar[4] = infocar[4].replace(",", ".");
			    double batCharge = Double.parseDouble(infocar[4]);
			    if (ElectricCar.isValidelectricPower(elecPower) == true)
				{if (ElectricCar.isValidbatteryCharge(batCharge) == true){
					cityCars.put(infocar[1], new ElectricCar(infocar[1], infocar[2], elecPower, batCharge));
					coches++;
					cochesEH++;}
				    else{}
				}else {}
			}else{}
		} else{}
			
		if (infocar[0].equals("H") == true) {
		    if (HybridCar.isValidPlate(infocar[1]) == true)
			{
			    int mhpower = Integer.parseInt(infocar[3]);
			    int mepower = Integer.parseInt(infocar[4]);
			    infocar[5] = infocar[5].replace(",", ".");
			    double bathCharge = Double.parseDouble(infocar[5]);
			    if (HybridCar.isValidmechanicalPower(mhpower) == true)
				{if (HybridCar.isValidelectricPower(mepower) == true)
					{if (HybridCar.isValidbatteryCharge(bathCharge) == true){
						cityCars.put(infocar[1], new HybridCar(infocar[1], infocar[2], mhpower, mepower, bathCharge));
						coches++;
						cochesEH++;}
					    else{}
					}else{}
				}else{}
			}else{}
		}else {}
		
	    }	    
	    
	} while(inputfichero.hasNext() == true); //SEGUIRA LEYENDO FILAS DE COCHES MIENTRAS HAYA CONTENIDO EN EL FICHERO
	
	inputfichero.close();
     }


    public Car getCarFromPlate(String plate) {
	return cityCars.get(plate);
    }


     public int computeTotalPower () {
	 int Power = 0;
         int TotalPower = 0;
	 ArrayList <Car> temp = new ArrayList<Car>(cityCars.values());
	 
	 Car[] arrayCityCars = temp.toArray(new Car[cityCars.size()]);
	 for (int i=0; i<cityCars.size(); i++) { //SUMAMOS EL VALOR TOTAL DE POTENCIA DE CADA TIPO DE COCHE
	     Power = arrayCityCars[i].getTotalPower();
	     TotalPower += Power;
	 }
	 return TotalPower;
    }

    public float computeAverageBatteryLevel() {
	
	double Power = 0;
	double TotalPower = 0;
	
	for (int i=0; i<cityCars.size(); i++) { //SUMAMOS EL VALOR TOTAL DE POTENCIA DE CADA TIPO DE COCHE
	    if (cityCars.get(i) instanceof ElectricCar) {
		Car cocheE = cityCars.get(i);
		Power = ((ElectricCar)cocheE).getBatteryCharge();
		TotalPower += Power;}
	    
	    if (cityCars.get(i) instanceof HybridCar) {
		Car cocheH = cityCars.get(i);
		Power = ((HybridCar)cocheH).getBatteryCharge();
		TotalPower += Power;}
		
	}
	return (float)TotalPower/cochesEH;
    }

    public void saveCarsToFile (String filename)throws FileNotFoundException {
    
	File fichero = new File(filename); //SE ABRE EL FICHERO A PARTIR DEL INPUT
	if (fichero.exists() == true) {
	    PrintWriter pw = new PrintWriter(fichero);
	    ArrayList <Car> temp = new ArrayList<Car>(cityCars.values());
	    Car[] arrayCityCars = temp.toArray(new Car[cityCars.size()]);
	    for (int i=0; i<cityCars.size(); i++) {
		String car = arrayCityCars[i].toString();
		if (car.contains(".") == true) {car = car.replace(".", ","); pw.println(car);}
		else{
		    pw.println(arrayCityCars[i].toString());}
	    }
	    pw.close();	
	}
    }
    
    private float intervalInHours(String inTime, String outTime) {
	int hi = Integer.parseInt(inTime.split(":")[0].trim());
	int mi = Integer.parseInt(inTime.split(":")[1].trim());
	int ho = Integer.parseInt(outTime.split(":")[0].trim());
	int mo = Integer.parseInt(outTime.split(":")[1].trim());
	int dif = (ho*60+mo)-(hi*60+mi);
	return ((float)dif/60);
    }

    public void increaseCarBatteryChargeLevel(String plate, String entryTime, String departureTime) {
	Car cochecast;
	ArrayList <Car> temp = new ArrayList<Car>(cityCars.values());
	for (int i=0; i<cityCars.size(); i++) {
	    if (temp.get(i).getPlate().equals(plate) == true && temp.get(i) instanceof ElectricCar) {
		cochecast = temp.get(i);
		float chargeTime = new CarDB().intervalInHours(entryTime, departureTime);
		((ElectricCar)cochecast).increaseBatteryChargeLevel(chargeTime);
	    }
	    if (temp.get(i).getPlate().equals(plate) == true && temp.get(i) instanceof HybridCar) {
		cochecast = temp.get(i);
		float chargeTime = new CarDB().intervalInHours(entryTime, departureTime);
		((HybridCar)cochecast).increaseBatteryChargeLevel(chargeTime);
	    }
	}
	
    }

    public void sortByPlate () {
	ArrayList <Car> temp = new ArrayList<Car>(cityCars.values());
	Collections.sort(temp);
	cityCars.clear();
	for (int i=0; i<cityCars.size(); i++) {
	    Car coche = temp.get(i);
	    cityCars.put(coche.getPlate(), coche);
	}
	
    }
    
    public void  sortByBatteryChargeAndPlate () {
	ArrayList <Car> temp = new ArrayList<Car>(cityCars.values());
	Collections.sort(temp, new CarComparatorByBatteryLevelAndPlate());
	cityCars.clear();
	for (int i=0; i<coches; i++) {
	    Car coche = temp.get(i);
	    cityCars.put(coche.getPlate(), coche);
	}
    }


    
	
}
Posted
Updated 27-Apr-22 23:24pm
v2
Comments
CPallini 28-Apr-22 5:13am    
Probably, you have to show more code, in order to get help.
Richard MacCutchan 28-Apr-22 6:50am    
I just tried something similar and it works correctly. You need to use the debugger to find out which variable is getting lost or destroyed.
[no name] 30-Apr-22 11:35am    
check how are implemented toString() methods in classes of stored cars. ie for CombustionCar it is like

public String toString() {
return "C;" +getPlate() +";"+ info2 +";" +power;
}

and check what is in input file ie
C;plate01;2;1000

it works for me (but I don't have your Car classes )

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