So recently I've got into this problem, that every time I try to add two+ cars(trucks, busses or vehicles) program gets null pointer reference. Seems like my array can only hold one object. Why is that? Array size is set to 200... Adding one object works like a charm. This also works on C#. But not in Java.
public class Town {
public int MaxNumberOfCars = 200;
public String Dealership;
public String Adress;
public String Phone;
public Car[] Cars = new Car[MaxNumberOfCars];
public Bus[] Busses = new Bus[MaxNumberOfCars];
public Truck [] Trucks = new Truck[MaxNumberOfCars];
public Vehicles[] Vehicles = new Vehicles[MaxNumberOfCars];
public static int carCount;
public static int busCount;
public static int truckCount;
public static int vehicleCount;
public int townVehicleCount;
public int DealershipCount;
public double avgage;
public Town(String dealership, String adress, String phone) {
Dealership = dealership;
Adress = adress;
Phone = phone;
}
public void AddCar(Car car) {
Cars[carCount++] = car;
vehicleCount++;
}
The code where I'm accesing the AddCar:
private static void Read(String text, Town[] towns) {
String text1 = text;
String dealership = null, adress = null, phone = null;
ArrayList<String> line = new ArrayList<>();
StringTokenizer st = new StringTokenizer(text1, "\n");
int count = st.countTokens()-3;
if (line != null) {
dealership = st.nextToken();
adress = st.nextToken();
phone = st.nextToken();
towns[townCount] = new Town(dealership, adress, phone);
for(int i = 0; i < count; i++) {
String string = st.nextToken();
String[] values = string.split(";");
String licenseplates = values[0]; // 004
char type = values[1].charAt(0);
String brand = values[2];
String model = values[3];
YearMonth yearofmake = YearMonth.parse(values[4]);
YearMonth techinspection = YearMonth.parse(values[5]);
String fuel = values[6];
int fuelconsumption = Integer.valueOf(values[7]);
switch (type) {
case 'c':
Car car = new Car(licenseplates, brand, model, yearofmake, techinspection, fuel, fuelconsumption);
towns[townCount].AddCar(car);
towns[townCount].AddVehicle(car);
break;
}
townCount++;
}
}
}
Your problem is that you are incrementing townCount without there being enough towns in your array towns. You need to either add more towns to your array, or delete the townCount++; line at the end of your for loop.
Why your count variables are static?
I think first you must change this. then you must add some validation like checking MaxNumberOfCars validation in your addCar method.
Related
I have an array and I want to assign values in group of 3s
Name, Id, Population, Name, Id, Population, Name, Id, Population etc.
Is there a way to do that?
This is what I have
while (scanner.hasNext()) { `
scanner.useDelimiter(",");`
list.add(scanner.nextLine());}`
for(int i=0; i<list.size(); i++){
String n = list.get(i);
System.out.println("Hopefully going thru " + n);} //for me to check
String ar =list.toString();
Object [] a = ar.split(",");// splitting the array for each string
for(int h=0;h<a.length;h+=3) { // for [0] += 3 is Name
for(int j=1;j<a.length; j+=3) { // for [1] += 3 is Id
for(int k=2; k<a.length;k+=3) { //for[2]+= is Population
String name = a[h].toString();
String id = a[j].toString();
String population = a[k].toString();
System.out.println("name is "+ name);// this is just to check correct values
System.out.println("id is "+ id);// this is just to check correct values
System.out.println("population is " +population);// this is just to check correct values
CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object`
I don‘t think that ar has the correct data and I don‘t understand why you don’t work with list directly, but assuming that ar has the correct data, it should be possible to use:
for(int = 0; i < ar.length ; ) {
var cityRow = new CityRow(
ar[i++],
ar[i++],
ar[i++]
);
// remember to add cityRow to an
// appropriate list
}
You use Scanner so no need to split an array. You can read each separate value one-by-one directly from it.
public class Main {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\n|,");
System.out.print("Total groups: ");
int total = scan.nextInt();
List<City> cities = readCities(scan, total);
printCities(cities);
}
private static List<City> readCities(Scanner scan, int total) {
List<City> cities = new ArrayList<>(total);
System.out.println("Enter each city on a new line. Each line should be: <id>,<name>,<population>");
for (int i = 0; i < total; i++) {
String id = scan.next();
String name = scan.next();
int population = scan.nextInt();
cities.add(new City(id, name, population));
}
return cities;
}
private static void printCities(List<City> cities) {
System.out.println();
System.out.format("There are total %d cities.\n", cities.size());
int i = 1;
for (City city : cities) {
System.out.format("City №%d: id=%s, name=%s, population=%d\n", i++, city.id, city.name, city.population);
}
}
static class City {
private final String id;
private final String name;
private final int population;
public City(String id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
}
}
public void crearCliente() {
int i, k, j, l;
registro r = new registro();
k = lr.getSize();
for (i = 0; i < k; i++) {
r = lr.get(i);
l = r.getSize();
String contenido[] = new String[8];
for (j = 0; j < l; j++) {
contenido[j] = r.getCampoR(j);
//System.out.println(contenido[j]);
}
c1 = new Cliente(contenido[0], contenido[1], contenido[2], contenido[3], contenido[4], contenido[5], contenido[6], contenido[7]);
c1.verCliente();}
In this code, at the end,I assign a value to c1, but when I print it i get null in all the c1 fields. I write my code down for the class Cliente.
I want to print all the values i gave to c1 but i do not know why it print null in all the fields. I follow the code using the debugger and everything is right until the sentences which assign all the values to the new variable.
public class Cliente {
private String Id_cliente;
private String Cod_postal;
private String Numero;
private String Calle;
private String Provincia;
private String Poblacion;
private String Telefono;
private String Apellidos;
public Cliente(String idc, String cp, String num, String cal, String prov, String pob, String tlf, String aps){
idc = Id_cliente;
cp = Cod_postal;
num = Numero;
cal = Calle;
prov = Provincia;
pob = Poblacion;
tlf = Telefono;
aps = Apellidos;
}
public void verCliente(){
System.out.println("Id_cliente: "+ Id_cliente);
System.out.println("Codigo postal: "+ Cod_postal);
System.out.println("Numero: "+ Numero);
System.out.println("Calle: "+ Calle);
System.out.println("Provincia: "+ Provincia);
System.out.println("Poblacion: "+ Poblacion);
System.out.println("Telefono: "+ Telefono);
System.out.println("Apellidos: "+ Apellidos);
}
}
You should change this
idc = Id_cliente;
to
Id_cliente = idc;.
You are assigning a values to your method parameters, rather than fields. Same applies to all of the parameters in your constructor Cliente.
Your assignments are backwards in your constructor. Switch the left and right hand sides of all those and it should work.
Your constructor for the class Cliente is switching assignement.
Change the idc = Id_cliente to Id_cliente = ic.
I am trying to read the input from a text file using scanner class and pass into an array. I know how to read the input using scanner class. The only problem I am facing here is I am unable to pass into the array.
public class ReadItemData {
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader(
"src//chapter11//Items.txt"));
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
System.out.println(code + " " + sku + " " + qty);
}
}
The above code works without the array concept. I want to extend the same concept to read the above data into a array of size 100. Any suggestions would be helpful. My final aim is to sort the input which is in array by code,sku
This is how I used comparable interface for sorting. How can I extend this concept for arrays?
I used something like this for sorting(without the array concept)
class Item implements Comparable {
private int qty;
private String sku,code;
public Item(int qty, String sku,String code) {
this.qty = qty;
this.sku = sku;
this.code = code;
}
public int getQty() {
return qty;
}
public String getSku() {
return sku;
}
public String getCode() {
return code;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getQty() < i.getQty())
{
return -1;
}
if (this.getQty() > i.getQty())
{
return 1;
}
return 0;
}
}
Thanks!!
String[] array = new String[100];
int currentIndex = 0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[currentIndex] = code;
array[currentIndex++] = sku;
array[currentIndex++] = ""+qty;
currentIndex++;
}
As mentioned in the comments, you can use 2D array of 100 rows and 3 columns like this:
Object[][] array = new Object[100][3];
int i=0,j=0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[i][j++] = code; // array of row i and columns j
array[i][j++] = sku;
array[i][j] = qty;
i++; // increment i since it's for rows
j=0;//reset j because it's for columns
}
I have successfully extracted data from 2 files and stored them in array objects in their respective classes. This is some of my data that i have stored in array objects:
2005,Arsenal,ManU,Arsenal,WestHam,Y,2,3,40000
2006,ManU,Chelsea,ManU,WestHam,N
2007,ManU,Arsenal,ManU,WestHam,Y,1,0,260000
2008,Chelsea,ManU,Chelsea,Swansea,Y,4,0,285630
2009,Chelsea,ManCity,Chelsea,Swansea,N
Each comma represents a different column. This is is my code to store it:
try{
Scanner kd = new Scanner(file);
while(kd.hasNext()){
String data = kd.nextLine();
String [] values = data.split(",");
String year = values[0];
String wScore = "N/A" , lScore = "N/A", crowd = "N/A";
if(inputYears.equals(year))
{
g.setPremier(values[1]);
g.setLosing(values[2]);
I did as suggested by some of the users but the only problem now is im getting the winner as blank.For example:
Year: 2005
Premier:
It should be:
Premier: Arsenal
Anyway i can fix that?
Well, if the users are going to query only by the year, then you should have a map with the year as a key.
In the init phase, try doing something like this:
Map<String, ArrayList<String>> map= new HashMap<String, ArrayList<String>>();
while(kd.hasNext()){
String data = kd.nextLine();
String [] values = data.split(",");
String year = values[0];
String premiers = values[1];
//String otherStuff= values[2]; and so on
ArrayList<String> temp= new ArrayList<String>();
temp.add(premiers);
//temp.add(otherStuff);
map.put(year, temp);
}
Later on, you can query like this:
ArrayList<String> values= map.get(userInputYear);
String winner= values.get(0);
No collections? Tough teacher you got there....
In the absence of a Map you could try creating a separate getPremiershipChampion method.
Like this:
public PremiershipYear getPremiershipChampion (String userYear, String[] kd) {
while(kd.hasNext()){
String data = kd.nextLine();
String [] values = data.split(",");
String year = values[0];
if (userYear.equals(year)) {
PremiershipYear py = new PremiershipYear();
py.setWinner(values[1]);
py.setRunnerUp(values[2]);
// Set whatever you need to here...
return py;
}
}
return null;
}
...then call it like this:
PremiershipYear year = getPremiershipChampion (userYear, kd);
// Get the winner
if (year != null) {
System.out.println("Winner for "+userYear+"="+year.getWinner());
}
Here is the PremiershipYear class:
public class PremiershipYear {
private String winner;
private String runnerUp;
private String third;
private String fourth;
private String faCupWinner;
private int someScore;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getRunnerUp() {
return runnerUp;
}
public void setRunnerUp(String runnerUp) {
this.runnerUp = runnerUp;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public String getFourth() {
return fourth;
}
public void setFourth(String fourth) {
this.fourth = fourth;
}
public String getFaCupWinner() {
return faCupWinner;
}
public void setFaCupWinner(String faCupWinner) {
this.faCupWinner = faCupWinner;
}
public int getSomeScore() {
return someScore;
}
public void setSomeScore(int someScore) {
this.someScore = someScore;
}
}
You can muck about with this to make it more efficient e.g. make kd class level, but this should give you the general idea!
Use a Map.
If you only have one year per line, use a HashMap<String, String> with the year as key and the team as value.
If you have many lines with identical years, use a HashMap<String, ArrayList<String>> with the year as key and the team*s* as values.
In the latter case, you must ensure the value is initialized. If not, you initialize it and ad d the current team. If it was already initialized, you get the value by year and add the current team to it.
Once you have the user input, you can query your Map's key set...
to verify it contains the user input, and if so...
to display the team / enumerate every team listed for that year
you could make a class to represent a record of your data
class Data
{
private String year;
private String winner;
...
Data(String year, String winner) { ... }
}
then you can fill a Map which associates a year with some data which makes looking-up the year a bit easier.
Map<String, Data> m = new HashMap<String, Data>();
while(kd.hasNext())
{
String[] arr = kd.nextLine().split(",");
Data d = new Data(arr[0], arr[1])
m.put(arr[0], d);
}
but even if you just had a List<Data> or Data[] etc you could still do something like
for (Data d : listOfData)
{
if (d.getYear().equals(yearToFind)) return d;
}
to find the year
I want to read from a txt file and I am using System.arraycopy to copy
parts[] to scores[].
I know that scores must be a String in order to work. My
constructor has to be an int[] array for scores. So scores is an int[]. Is there any solution?
private void processLine(String line) {
String mygoden1 = "";
//String mygoden2 = "";
try {
String parts [] = line.split(",");
mygoden1= parts[0];
Name name = new Name(parts[1]);
int gN1=Integer.parseInt(mygoden1);
String gL= parts[3];
//gL = gL.trim();
String gC = parts[4];
gC=gC.trim();
int scoresLength = parts.length-4;
String scores[]=new String[scoresLength];
System.arraycopy(parts,4,scores, 0, scoresLength);
Gamer g1 = new Gamer(gN1 ,name,scores, gL, gC);
this.add(g1);
}
This is my constructor:
public class Gamer {
private int gnumb; //The Gamers Number g -> is for gamer
private Name gamerName;
private String glevel;
private String gCountry;
private static final int SCORES_1 =5;
private int [] scores;
//}
public Gamer(int gN ,Name name, int gS[], String gL , String gC)
{
gnumb = gN;
gamerName=name;
scores = new int [SCORES_1];
scores=gS;
glevel =gL;
gCountry =gC;
}
I would replace
String scores[]=new String[scoresLength];
System.arraycopy(parts,4,scores, 0, scoresLength);
with
int[] scores = new int[scoresLength];
for(int i = 0; i < scoresLength; i++)
scores[i] = Integer.parseInt(parts[i + 4]);
Don't use System.arraycopy when you need to transform data. Iterate over parts and parseInt() each element, then store it in scores.