How come my array is null when writing data to it? - java

I am trying to figure out why my program says my array is null and cannot be written to. I created an Element class to determine what elements would be in the array, so the array is type Element[]. The array takes in data from a file and then is supposed to add it to the array. The program seems to read the data from the file but it will not add it to the array.
class Array extends Element
{
//Global Variables
public static Element[] array;
//Max number of entries
private int numMax;
public int numElements;
//Constructors
public Array()
{
}
public Array(int numMax)
{
//Instantiate the array
array = new Element[numMax];
numElements = 0;
}
This is a function to insert the data into the array:
public void insertValue(String firstName, String lastName,
String company, String address, String city, String state,
String county, String phone, int zip, long key, int rowNum)
{
try
{
//Add elements to array
System.out.println(numElements);
array[numElements].setFirstName(firstName);
array[numElements].setLastName(lastName);
array[numElements].setCompany(company);
array[numElements].setAddress(address);
array[numElements].setCity(city);
array[numElements].setState(state);
array[numElements].setCounty(county);
array[numElements].setPhone(phone);
array[numElements].setZip(zip);
array[numElements].setKey(key);
array[numElements].setRowNum(rowNum);
//Increment number of elements in the array
numElements++;
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}
This is my input function:
public static void readInputFile()
{
//Create a new instance of the array class so that the array can be
//written to without creating a new array for either merge or insert
//sort
Array arr = new Array(1000010);
Element[] array = arr.getArray();
try
{
fileRead = new FileReader(fileLocation);
br = new BufferedReader(new FileReader(fileLocation));
//Allows the first line of the file that includes the titles to
//not be added to the array
String line = br.readLine();
//Counter for iterating through array
int elemCntr = 0;
while (elemCntr != 10)
{
//Variables
String lineline = br.readLine();
//This will split the line into sections based on the
//placement of comas: split data into sections
String[] readLine = lineline.split(",");
firstName = readLine[0];
lastName = readLine[1];
company = readLine[2];
address = readLine[3];
city = readLine[4];
county = readLine[5];
state = readLine[6];
zip = Integer.parseInt(readLine[7]);
phone = readLine[8];
key = Long.parseLong(readLine[9]);
rowNum = arr.numElements + 1;
//Insert data into array
arr.insertValue(firstName, lastName, company, address, city,
state, county, phone, zip, key, rowNum);
}
} catch (Exception e){
// do something
}
}
Can you identify any problems, please?

Try with using ArrayList
You are trying to make dynamic array of class Element which is possible.But it is bad practice as u have to write initialization statement for every element.Initialization are meant to be done in constructors.
Declaration: Element element[] = new Element[5];
Initialization: element[0] = new Element();
;
It is possible to make dynamic arrays of int , string etc easily then of Class.
PS: Try giving different names you are having Arrays as class and arrays as variable also.

your code is n't clear, but if you call readInputFile method first, it will instantiate array and then when you call insertValue method it should work properly, because array is static.

Related

How do I import a populated ready-made ArrayList from another class in java?

I'm working with a large set of imported data and retrieving certain parts of it in the main method with 2 classes(WeatherStation, WeatherReading).The data is temperature readings at loads of weather stations(station id, name, lat, lon, year, time, temp etc) I made a third class (SoloSiteIds) whose sole purpose was to return a whole and complete ArrayList of the site ids with no duplication. But I cannot import the ArrayList from the other class into my main method. My SoloSiteIds class looks like this:
public class SoloSiteIds {
static ArrayList <Integer> siteIds = new ArrayList <Integer>();
public SoloSiteIds() {
}
public SoloSiteIds( ArrayList <Integer> siteIds) {
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ",
String siteid = elements[0]; // convert all the site id's at index 0 to integers
int id = Integer.parseInt(siteid);
if(!siteIds.contains(id)) {
siteIds.add(id);
}
this.siteIds=siteIds;
}
}
}
public static ArrayList<Integer> getSiteIds() {
return siteIds;
}
public ArrayList<Integer> setSiteIds(ArrayList<Integer> siteIds) {
return this.siteIds = siteIds;
}
}
The main method where I am trying to import the ArrayList "siteIds" looks like this:
WeatherStation thisStation = new WeatherStation (id, name, lat, lon);
WeatherReading thisReading = new WeatherReading(year, month, date, hour, windSpeed, temp);
SoloSiteIds siteList= new SoloSiteIds();
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ","
String siteid = elements[0]; // convert all the site id's at index 0 to integers
id = Integer.parseInt(siteid);
thisStation.setId(id);
thisStation.setName(elements[1]);
//parse the different elements into different data types
String stringLat = elements[2];
lat= Double.parseDouble(stringLat);
lat = thisStation.setLat(lat);
lat=thisStation.setLat(lat);
String stringLon = elements[3];
lon= Double.parseDouble(stringLon);
lat = thisStation.setLon(lon);
lat=thisStation.setLon(lon);
String stringTemp=elements[9];
temp=Double.parseDouble(stringTemp);
temp=thisReading.setTemp(temp);
Only the top part is relevant. I have tried lots of different variation of .set and .get using "thisList" instance and a new ArrayList like
ArrayList<Integer> siteIds = thisList.setSiteIds();
ArrayList<Integer> siteIds= SoloSiteIds.getSiteIds();
thisList=Siteids.setSiteIds();
thisList=SingleSoloSites.setSiteIds();
etc etc. This might look stupid but im just showing Ive tried numerous things and i am stuck
Thanks
I believe your problem is that you are initializing siteIds as an empty Arry list but you are not setting the data in a static way (the set Method is not static).
As far as I am aware of your situation, I belive that the SoloSiteIds class is unnescessary. I would solve your problem with an ArrayList declared in your main class and initialize with a getSoleIds() method also declared in your main class.
The getSoleIds() Method should contain the code currently in the SoleSiteIds initializer.

What is the proper way to store a String array in an ArrayList?

I have a function which selects data from the database and then tries to store it in an ArrayList.
I want to store each individual columns in a ResultSet in a String array first, and then add the array in the ArrayList.
public void buildConnection() throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement statement =connection.createStatement();
ResultSet rSet=statement.executeQuery("select * from details");
ResultSetMetaData rSetMd=rSet.getMetaData();
int ColumnsNo=rSetMd.getColumnCount();
ArrayList<String[]> arrMatrix=new ArrayList<String[]>();
int j=0;
while(rSet.next()){
String arrRows[] = new String[ColumnsNo];
for(int i=1;i<=ColumnsNo;i++){
arrRows[i-1]=rSet.getString(i);
}
arrMatrix.add(j,arrRows);
j++;
}
System.out.println(arrMatrix.get(0)[0]+" "+arrMatrix.get(0)[1]+" "+arrMatrix.get(0)[2]);
System.out.println(arrMatrix.get(1)[0]+" "+arrMatrix.get(1)[1]+" "+arrMatrix.get(1)[2]);
}
The problem is that only the last entry from the database shows up in the arraylist. All the other entries are getting lost. Please tell me what I am doing wrong.
UPDATE:
the output:
1 Axel Namek
1 Axel Namek
where in my database this entry is the last one
I would use;
ArrayList<ArrayList<String>> in place of ArrayList<String[]>.
Using this method you are then able to;
ArrayList<ArrayList<String>> arrMatrix = new ArrayList<ArrayList<String>>();
arrMatrix.add(new ArrayList<String>());
arrMatrix.get(0).add("string value");
System.out.println(arrMatrix.get(0).get(0));
//string value
Though, i suspect this is not what you are after either. a better approach is to create a new class with first and surname fields and referencing those
public class Names {
public String firstname = null;
public String surname = null;
public Names(String first, String sur) {
firstname = first;
surname = sur;
}
}
from that point on;
Names instance = new Names("John", "Doe");
System.out.println(instance.firstname); // John
System.out.println(instance.surname); // Doe
It is trivial at the point to create an arraylist of names. Obviously, this example can be build on more.
I question your underlying motives you must be doing something else with the array, or you would just print it in the loop.

How do you initialize a default constructor for String Arrays?

I am trying to add a default constructor to my data type. Right below the default constructor is the problem,"ingredients = " " ; ". It gives me an error saying String cannot be converted to String[]. What do I put after the equals sign to make it compile?
import java.util.Arrays;
class Recipes {
private String[] ingredients = new String[20];
private String[] instructions = new String[20];
public Recipes(){
ingredients = "" ;
instructions = "" ;
}
public String[] getIngredients() {
return ingredients;
}
public void setIngredients(String[] inIngredients) {
ingredients = inIngredients;
}
public String[] getInstructions() {
return instructions;
}
public void setInstructions(String[] inInstructions) {
instructions = inInstructions;
}
public void displayAll() {
System.out.println("The ingredients are " + ingredients);
System.out.println("The instructions are " + instructions);
}
}
It doesn't make sense to assign a String ("") to String[] (an array of Strings).
You may want to do one of the following in your default constructor, depending on your requirements:
Do nothing. The arrays were already initialized when they were declared, even if they are full of null elements.
Assign the empty string "" to every element. You can use a for loop for that, or an array initializer.
Assign null to the arrays. You are presumably replacing the array references later by calling setIngredients and setInstructions.
You are initializing a String array reference to a single string value thats why the compiler is going nuts.
You can do this
class Recipes {
private String[] ingredients = null;
private String[] instructions = null;
public Recipes(){
ingredients = new String[5]{"","","","",""};
instructions = new String[5]{"","","","",""};
}
I've reduced the size of the array for brevity. You can also use a for loop to assign fill in empty strings in the array if the array size is too large.
class Recipes {
private String[] ingredients = new String[20];
private String[] instructions = new String[20];
public Recipes(){
for(int i=0;i<ingredients.length;i++)
{
ingredients[i]="";
instructions[i]="";
}
}

How to tokenize a file and input the data into an array?

I have a file of information separated by commas of which I need to tokenize and place into arrays.
The file has info such as
14299,Lott,Lida,22 Dishonest Dr,Lowtown,2605
14300,Ryder,Joy,19 Happy Pl,Happyville,2701
and so forth. I need to tekonize those pieces of information of which is separated by a comma. I'm not sure how to write out the tokenizer code to make it separate. I've managed to count the amount of lines in the document with;
File customerFile = new File("Customers.txt");
Scanner customerInput = new Scanner(customerFile);
//Checks if the file exists, if not, the program is closed
if(!customerFile.exists()) {
System.out.println("The Customers file doesn't exist.");
System.exit(0);
}
//Counts the number of lines in the Customers.txt file
while (customerInput.hasNextLine()) {
count++;
customerInput.nextLine();
}
And I also have the class of which I'll be placing the tokenized info into;
public class Customer {
private int customerID;
private String surname;
private String firstname;
private String address;
private String suburb;
private int postcode;
public void CustomerInfo(int cID, String lname, String fname, String add, String sub, int PC) {
customerID = cID;
surname = lname;
firstname = fname;
address = add;
suburb = sub;
postcode = PC;
}
But after this point I'm not sure how to place the info into the arrays of the customer. I've tried this but it's not right;
for(i = 0; i < count; i++) {
Customer cus[i] = new Customer;
}
It's telling me the 'i' and the new Customer are errors as it 'can't convert Customer to Customer[]' and 'i' has an error in the token.
first, you need to declare the Customer Array:
Customer[] cus = new Customer[count];
Now, the programm knows, how much space it has to allocate on the memory.
Then, you can use your loop, but you have to call the constructor of the class Customer and give him all the information it needs to create a new one :
for(i = 0; i < count; i++) {
Customer cus[i] = new Customer(cID, lname, fname, add, sub, PC);
}
Another thing you would be asking yourself about is, how do i get the data from the Strings/lines into the array.
for that, you should write all lines in an ArrayList. Like this.
ArrayList<String> strList = new ArrayList<String>();
while (customerInput.hasNextLine()) {
count++;
strList.add(customerInput.nextLine());
}
Now you got all lines as Strings in an ArrayList. But you want to give the single values of each String to your constructor.
take a look at the split method from Strings. (How to split a string in Java).
With split() you can split one line like this:
String[] strArray = "word1,word2,word3".split(",");
then in the strArray you can find your data:
strArray[0] would have the value "word1";
strArray[1] = "word2";
and so on
If it is a CSV file instead of a simple comma separated flie, maybe consider some library like:
Commons CSV
OpenCSV

How to organize array with different types?

Hi,
I am new in Java and trying to figure out how to push this data into array(6 rows, 3 columns)?
x1 John 6
x2 Smith 9
x3 Alex 7
y1 Peter 8
y2 Frank 9
y3 Andy 4
Afterwards, I will take numbers from last column for making mathematical calculations.
This is my code...
public class Testing {
public static void main(String[] args) {
Employee eh = new Employee_hour();
Employee_hour [] eh_list = new Employee_hour[6];
eh_list[0] = new Employee_hour("x1", "John", 6);
eh_list[1] = new Employee_hour("x2", "Smith", 9);
eh_list[2] = new Employee_hour("x3", "Alex", 7);
eh_list[3] = new Employee_hour("y1", "Peter", 8);
eh_list[4] = new Employee_hour("y2", "Frank", 9);
eh_list[5] = new Employee_hour("y3", "Andy", 4);
print(eh_list);
}
private static void print(Employee_hour[] mass){
for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i] + " ");
}
System.out.println();
}
}
But I'm getting this as the output...
testing.Employee_hour#1a752144 testing.Employee_hour#7fdb04ed
testing.Employee_hour#420a52f testing.Employee_hour#7b3cb2c6
testing.Employee_hour#4dfd245f testing.Employee_hour#265f00f9
How can I get numbers from last column?
Why not create a specific Java bean for your records?
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
}
And then use it like this:
Person [] people = new Person[10];
people[0] = new Person("x1", "John", 6);
...
Or better yet employ java.util.List instead of the array.
Field Access
In order to access separate fields, you either need to make your fields public (very bad idea) and simply refer to them as object_instance.field_name, or provide so-called getters:
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
public int getAnotherNumber() {
return anotherNumber;
}
}
Then call it when printing:
for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i].getAnotherNumber() + " ");
}
Why what you tried didn't work:
System.out.println(mass[0]) in your case will print the whole object representation, by default it prints what it did in your case. To do it nicer you need to override Object's String toString() method:
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
public String toString() {
return "{id="+id+", name="+name+", anotherNumber="+anotherNumber+"}";
}
}
Java is strongly typed, so you can't just make an array that will accept any type.
However, you could make a multidimensional array of type Object, and use java.lang.Integer for the integer values.
The alternative is to make a class that represents the rows in your table, and make an array of that class.
If you want to store it as array user 2 dimentional array.Here is a sample.
String[][] a2 = new String[10][5];
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
a2[i][j] = i;
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
}
The better approach would be to cretae an Object
class User {
String id;
String userName;
int userSomeValue;
//
}
Then push it to a list
User ob1=new User();
// set the values.
List<User> userList=new ArrayList<User>();
userList.add(ob1);
Use this list for procesing by retriving the contents using
userList.get(index);
Array is a type-safe collection you can use array of generic objects. Other way use collection Api.
There are some ways to store your data in an array but you can only store values of the same type in one Array. For Example just String, int or float. In your case you have to use String but you can't do any calculations with a string type variable even if it contains a number. I would suggest the way maksimov describes.

Categories

Resources