Cannot figure out why the array displays null - java

I want to read a txt file and store each record in the file to an array of objects called data[]. Everything works except the record parts are not being assigned correctly in the data[].
This is the format for the record.txt...
4252 4 item1
2435 23 item2
4355 16 item3
so on and so on...
I want to keep using the methods I have been using even if there is an easier way (there always is).
Thank you much ...
import java.util.Scanner;
import java.io.*;
public class SortsTest
{
private static Data[] data;
private static String file_to_read;
private static int num_of_records,
current_record = 0;
private final static int RECORD_DATA = 3;
private static Scanner scan_file1;
public static void main(String[] args) throws IOException
{
try {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a file name: ");
file_to_read = scan.next();
System.out.print("\nInput file = " + file_to_read);
System.out.print("\n# of records = ");
num_of_records = scan.nextInt();
scan_file1 = new Scanner(new File(file_to_read));
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
data = new Data[num_of_records];
String record[] = new String[RECORD_DATA];
for(int i = 0; i < RECORD_DATA; i++)
{
String line = scan_file1.next();
record[i] = line;
}
data[current_record] = new Data(record[0],record[1], record[2]);
current_record++;
}
//--------------------------------------------------------------------
//System.out.print("\n\nRecord 10: " + data[10].getPartName() + " " + data[10].getQuantity() + " " + data[10].getPartNumber());
System.out.print("\n\nRecord 10: " + data[10]);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
///////////////////////////// Data file /////////////////////////////////
import java.util.Scanner;
import java.io.*;
public class Data
{
private int part_num,
quantity;
private String part_name;
private Scanner scan_file1;
public Data(String part, String quan, String name)
{
part_num = Integer.parseInt(part);
quantity = Integer.parseInt(quan);
part_name = name;
}
public void setPartNumber(int num)
{
part_num = num;
}
public void setQuantity(int quan)
{
quantity = quan;
}
public void setPartName(String name)
{
part_name = name;
}
public int getPartNumber()
{
return part_num;
}
public int getQuantity()
{
return quantity;
}
public String getPartName()
{
return part_name;
}
}

You create a new empty data array every iteration through the while loop, try this:
data = new Data[num_of_records];
while (scan_file1.hasNext())
{

without going too deep into your code, I suspect this is part of your issue:
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
// you recreate your array every loop iteration
data = new Data[num_of_records];
instead, you need to do the following:
//---------------------- populate data array ------------------------
data = new Data[num_of_records];
while (scan_file1.hasNext())
{

Related

Read from a txt file and assign the value of lines to class fields

if anyone can help please ,
i have an issue assign the values from a text file to the class fields.
i have created a class called process and it has a fields like
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
my motive is to assign 1block in the file to agent separated by space another block to request type and so on...
say Agent3 R F 10 1 here Agent3 is going to be assign to agent and R going to assign to request_type F to class_type, 10 to num_of_seats,1 to arrivaltime
i am using arraylist to saveinput file (not compulsory i know this only thats y) and another arraylist to save the objects of my class.i am using substring method to assign the values manually is there any way instead of that so that i can simply take block which is seprated by space and do my job.
The input file(input.txt is )
Agent1 R F 2 0
Agent3 R F 10 1
Agent1 C F 1 4
Agent2 C B 2 1
Agent2 R B 10 0
................................................................................
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* #author Navdeep
*
*/
class Process
{
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
public Process()
{
setProcess("0", null, null, "0", "0");
}
public Process(String a, String b,String c,String d,String e)
{
setProcess(a,b,c,d,e);
}
public void setProcess(String a, String b,String c,String d,String e)
{
setAgent(a);
setRequest_type(b);
setClass_type(c);
setNum_of_seats(d);
setArrivaltime(e);
}
public void setAgent(String a){
agent = a;
}
public void setRequest_type(String b){
request_type = b;
}
public void setClass_type(String c)
{
class_type = c;
}
public void setNum_of_seats(String d) {
num_of_seats = d;
}
public void setArrivaltime(String e)
{
arrivaltime=e;
}
public String getAgent(){
return agent;
}
public String getRequest_type(){
return request_type ;
}
public String getClass_type()
{
return class_type;
}
public String getNum_of_seats() {
return num_of_seats ;
}
public String getArrivaltime()
{
return arrivaltime;
}
#Override
public String toString() {
return String.format("%s,%s,%s,%s,%s",getAgent(),getRequest_type(),getClass_type(),getNum_of_seats(),getArrivaltime());
}
}
public class main
{
public static void main(String[] args) throws FileNotFoundException
{
File temp = new File(args[0]);
Scanner sc = new Scanner(temp);
ArrayList<String> input = new ArrayList<String>();
while(sc.hasNext())
{
input.add(sc.nextLine());
}
List<Process> mylist = new ArrayList<Process>();
for (int i= 0; i <input.size();i++)
{
Process processobject = new Process();
processobject.setAgent(input.get(i).substring(0, 6));
processobject.setRequest_type(input.get(i).substring(7,8));
processobject.setClass_type(input.get(i).substring(9,10));
if(input.get(i).length() == 15)
{
processobject.setNum_of_seats(input.get(i).substring(11,13));
processobject.setArrivaltime(input.get(i).substring(14,15));
}
if(input.get(i).length() == 14)
{
processobject.setNum_of_seats(input.get(i).substring(11,12));
processobject.setArrivaltime(input.get(i).substring(13,14));
}
mylist.add(processobject); // fill arraylist with objects of my class
}
System.out.println("array list of the input from the file" + input);
System.out.println("\n \nobjects in my list"+ mylist);
}
}
the overall motive of my project is to sort the objects according to the field priorities.
If your objective is to create Process class instance then you can use the following code:
while(sc.hasNext())
{
String line = sc.nextLine();
String elements[] = line.split(" ");
Process processobject = new Process();
processobject.setProcess(elements[0],elements[1],elements[2],elements[3],elements[4]);
}
You can improve the your setProcess method by setting accessing directly class attributes with this reference. Also you can pass the same parameters to Process class constructor then you won't need setProcess method. Check the below code.
public Process(String agent, String request_type, String class_type, String num_of_seats, String arrivaltime) {
this.agent = agent;
this.request_type = request_type;
this.class_type = class_type;
this.num_of_seats = num_of_seats;
this.arrivaltime = arrivaltime;
}
Try this:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(configFileName).getFile());
input = new FileInputStream(someFilePath);
prop.load(input);
String someString=prop.getProperty("someString");
int someintValue=new Integer(prop.getProperty("someintValue"));

Creating an ArrayList of Employees

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}
The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.
When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

Array outputs random sequence of characters instead of desired result

I am attempting to write a program that will output data received from a csv file. The CSV file is composed of 28 or so strings/lines with each data in the line separated by a comma into 5 categories (Team name, League, Coaches, Division and Full Time).
I actually have a couple of issues...
When i run my program, i receive a random sequence of characters (such as: [Ljava.lang.String;#5e34d46a) in my coaches category instead of a name that i am expecting. Does this have something to do with it being in an array? How would i solve it.
The categories for each string are displayed in the output as a list, i would like to output the data of strings into a line. For example, instead of the output displaying:
Team name: Team A
League: Western Conference
Coaches: [Ljava.lang.String;#1c751d58
Division: 2
Full Time: true
I would like it to be displayed as a line.
The last category of a single instance of a string in the output is attached to the first category of the next string. Like so: Full Time: trueTeam name: Team A. How would i separate this?
My Team.java code:
public class Team
{
private String name;
private String league;
private String[] coaches;
private String division;
private boolean fullTime;
public Team(String dataLine)
{
String[] data = dataLine.split(",");
this.name = data[0];
this.coaches = getStringAsArray(data[1], ":");
this.league = data[2];
this.division = data[3];
this.fullTime = data[4].equals("yes");
}
public Team(){
}
private String[] getStringAsArray(String t, String delimiter)
{
String[] result = t.split(delimiter);
return result;
}
private String getArrayAsString(String[] coaches)
{
coaches = this.getCoaches();
String result = "";
for(int i = 0; i<coaches.length; i++)
{
result += coaches[i] +" ";
}
result = result.trim();
return result;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setCoaches(String coaches)
{
this.coaches = getStringAsArray(coaches, ":");
}
public String getCoachesAsString()
{
String result = getArrayAsString(coaches);
return result;
}
public boolean isFullTime() {
return fullTime;
}
public void setFullTime(boolean fullTime) {
this.fullTime = fullTime;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String[] getCoaches() {
return coaches;
}
public void setCoaches(String[] coaches) {
this.coaches = coaches;
}
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#Override
public String toString() {
return "Team name: " + name + "\nLeague: " + this.league + "\nCoaches: " + this.coaches + "\nDivision: " + this.division + "\nFull Time: " + this.fullTime;
}
}
My StoreData.java code:
import shiftershape.model.Team;
import java.util.ArrayList;
public class StoreData {
public static ArrayList<Team> teams = new ArrayList<Team>();
public static String getTeams()
{
String s = "";
for(int i = 0; i < teams.size(); i++){
s += teams.get(i);
}
return s;
}
public static ArrayList<Team> TeamListFromArray(String[] as)
{
ArrayList<Team> teams = new ArrayList<Team>();
// for( int i= 0 ; i < as.length; i++){
for (String s: as){
teams.add(new Team(s));
}
return teams;
}
}
My ReadCSV.java code:
import Utilities.StoreData;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import shiftershape.model.Team;
public class ReadCsv {
public void readCsv() {
String csvFileToRead = "C:/Users/Fryyy/Desktop/FootballRepo/TestData/football_teams_phase1.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
int i = 0;
while ((line = br.readLine()) != null) {
Team one = new Team(line);
if(i > 0){
StoreData.teams.add(new Team(line));
}else{
i++;
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static ArrayList<Team> getTeams() {
return StoreData.teams;
}
public static void setTeams(ArrayList<Team> teams) {
StoreData.teams = teams;
}
}
My FootballC.java code:
import Utilities.StoreData;
import shiftershape.model.Team;
public class FootballC {
public static void main(String[] args)
{
ReadCsv junk = new ReadCsv();
junk.readCsv();
System.out.println(StoreData.getTeams());
}
}
System.out.println(StoreData.getTeams()); will call toString() on String[]
try this:
for (String s : StoreData.getTeams()) {
System.out.println(s);
}
[Ljava.lang.String;#5e34d46a) is the resource code for an object when printed to standard out. In this case being a string, so somewhere it looks like you're printing an array instead of the value within the array, causing the resource ID to be shown instead of the values within, as Java doesn't print array contents by default.
[Ljava.lang.String;#1c751d58 is the String version of an array. Arrays don't have a nice toString() method. If you used Lists in stead of Arrays it will print better.
The quick conversion of an array to a list is Arrays.asList(array);

printf statement working for one instance of the same class but not another

this is my first time posting so hopefully all goes well. I am having a problem with the following program.
public class Project3 {
public static String fName = "drum_members.txt";
private static Scanner fin;
private static PrintWriter fout;
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
String membershipLength;
Member m_1 = new Member();
Member m_2 = new Member();
Member m_3 = new Member();
Member m_4 = new Member();
try {
fin = new Scanner(new File(fName));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + fName);
System.exit(1);
}// end try
m_1.Member();
m_1.calculateFreeItems();
m_1.printMember();
m_2.Member();
m_2.calculateFreeItems();
m_2.printMember();
m_3.Member();
m_3.calculateFreeItems();
m_3.printMember();
m_4.Member();
m_4.calculateFreeItems();
m_4.printMember();
}
public static class Member{
public int id;
public String name;
public String nickName;
public int monthsMembership;
public String favoriteItem;
public int freeItems;
public void Member()
{
name = fin.next();
nickName = fin.next();
monthsMembership = fin.nextInt();
favoriteItem = fin.next();
fin.nextLine();
}
private int calculateFreeItems()
{
freeItems = monthsMembership/12 +1;
return (freeItems);
}
public void setFavoriteitem()
{
System.out.print("Enter new favorite item: ");
favoriteItem = keyboard.next();
}
private String calculatemembershipLength()
{
if(monthsMembership < 12)
return (monthsMembership + "months,");
else
return (monthsMembership/12 + " years, " + monthsMembership%12 + " months,");
}
public void printMember()
{
String months = this.calculatemembershipLength();
System.out.printf("Member #1 - NAME: %22s, NICKNAME:%22s, MEMBER SINCE: %22s FAVORITE ITEM:%22s, FREE ITEMS PER MONTH: %d\n",
name, nickName, months, favoriteItem, freeItems);
}
}
}
After debugging all I know is that the printf statement doesn't work the THIRD time, it will work the 4th time no problem. Any help would be greatly appreciated, and thanks for your time.

keep showing that:"java.lang.NullPointerException"

I want to read contents from a text file and then set it to some variables in car class. But it keeps showing me that "java.lang.NullPointerException". I don't know what's wrong with it. Could someone tell me what to do?
The error line is cars[0].setRegion(tokens[2]);
Here's the text file.
CarInLot KLM456 ND Meter4 120
CarInLot VMK123 ME Moving 0
CarInLotDKC003 WA Meter5 30
Meter1 None 10
CarInLot IML84U ND Meter6 800
Here's the test class.
import java.util.Scanner;
import java.io.*;
public class test
{
public static void main(String[] args) throws IOException
{
// Get the filename.
String filename = "input.txt";
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
if(filecotent.startsWith("Meter")){
cars[0].setPlate(tokens[1]);
}
}
System.out.println(cars[0].toString());
// Close the file.
inputFile.close();
}
}
Here's car class.
public class Car {
private String plate;
private String region;
private int minutes;
public Car(String carPlate, String carRegion,
int carMinutes) {
plate = carPlate;
region = carRegion;
minutes = carMinutes;
}
public Car(Car object2) {
plate = object2.plate;
region = object2.region;
minutes = object2.minutes;
}
public void setPlate(String pl) {
plate = pl;
}
public void setRegion(String re) {
region = re;
}
public void setMinutes(int mi) {
minutes = mi;
}
public String getPlate() {
return plate;
}
public String getRegion() {
return region;
}
public int getMinutes() {
return minutes;
}
public String toString() {
String string = "Car's information: "
+ "\n"
+ "\nLicense Plate: " + plate
+ "\nLicense Plate Resgistration Region: " + region
+ "\nParked time" + minutes
+ "\n";
return string;
}
}
So you've got this code
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
...
cars is initialized, but the elements inside it aren't. You need to initialize those first, otherwise they are null and you get NullPointerException.
cars[someIndex] = new Car(...);
Also, the way you have your code now, you'll always be overwriting the same Car reference in the array, ie. the one at index 0. You may want to use an incrementing index to initialize each element.

Categories

Resources