ADT not accessing other class, constructors not working - java

I'm trying to create a Node class and I want the default to be all 0's and null and then when I call the node class with constructors i want to set them. and with the code I have set now I just keep getting
symbol: method Node(int,int,java.lang.String)
location: variable n1 of type Node
I don't understand what's wrong with my default constructor cause it will only work when I delete it.
class Node{
private int ticks;
private int jobId;
private String name;
private Node next;
public Node(){
next = null;
ticks = 0;
jobId = 0;
name = " ";
}
public Node(int t,int j, String name){
ticks = t;
jobId = j;
name = name;
}
//sets next to node
public void setNext(Node next){
next = next ;
}
}//end class node
MAIN---------------------------------------------------------
public class lab3{
public static void main(String[] args) throws Exception{
//Open File
File file = new File("p3.dat");
Scanner in = new Scanner(file);
int jobId = storeJobIdNum(in);
int ticks = storeTicks(in);
String name = storeName(in);
Node n1 = new Node();
n1.Node(ticks,jobId,name);
jobId = storeJobIdNum(in);
ticks = storeTicks(in);
name = storeName(in);
// String line = in.nextLine();
// String name = line;
//System.out.println(jobId+" "+num+" "+numTicks);
// n1.setNode(,,);
}//end main
public static String storeName(Scanner in){
String name = in.next();
System.out.println(name);
return name;
}
public static int storeJobIdNum(Scanner in){
int num = in.nextInt();
System.out.println(num);
return num;
}
public static int storeTicks(Scanner in){
int num = in.nextInt();
System.out.println(num);
return num;
}
}//end class
p3.dat looks like ==> 1 4 name
and has a few lines that differ.

Once the object is created, you won't be able to invoke another constructor with it. Instead, create a method that takes care of changing the fields.
Put this as your method call to set the attributes:
Node n1 = new Node();
n1.set(ticks,jobId,name);
And then in Node, use this instead of another constructor:
public void set(int t,int j, String name){
this.ticks = t;
this.jobId = j;
this.name = name;
}
You'll generally hear these be called "setter" methods.

Related

Binary Search Tree (BST) search method for string

i've built a BST that have elements of (country code(string), indicator code(string), indicator name(string) and ArrayList of Years(int) and values(string)).
I'm trying to figure out how to prompt the user to search by entering Indicator code and then the year which the output will be the value.
it would be much appreciated if you could show how to code the search method cause I've tried everything.
I've tried this in the BST class. but it doesn't feel right(?)
public void search(Indicator indicator, String searchTerm){
String str = (String)indicator.getICode();
int n1 = str.compareTo(searchTerm);
int n2 = searchTerm.compareTo(str);
if (str == null || str.equalsIgnoreCase(searchTerm)){
return str;
}
if (n1 > n2){
return search(indicator, searchTerm);
}
else if (n1 < n2){
return search(indicator, searchTerm);
}
}
this is my application class:
public class BigDataBST{
public static void main (String [] Args) throws IOException {
try{
BST bigdata = new BST();
MyData d1;
File inFile = new File ("Indicator.txt");
FileReader fr = new FileReader (inFile);
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
while(str != null ){
StringTokenizer st = new StringTokenizer(str,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct = new Indicator (cCode,iName,iCode,data);
bigdata.insertNode(idct);
str = br.readLine();
}
TreeNode class:
TreeNode left;
TreeNode right;
Indicator idct;
public TreeNode(Indicator id){
left = right = null;
idct = id;
}
indicator class:
private String cCode; //country code
private String iName; //indicator Name;
private String iCode; //indicator code;
public ArrayList <MyData> DataList;
public Indicator(){
cCode = null;
iName = null;
iCode = null;
DataList = null;
}
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
//setter & getter method for attributes iCode,iName and cCode
//toString method
MyData class:
private int year;
private String value;
public MyData(){
year = 0;
value = null;
}
public MyData(int year, String value){
this.year = year;
this.value = value;
}
//setter & getter method for attributes year and value
//toString method
example of indicator.txt:
(from left: cCode; iName; iCode; values)
MYS; Employment in industry (% of total employment) (modeled ILO estimate); SL.IND.EMPL.ZS;
29,08600044;28,56900024;28,36300087;28,02300072;27,51600075;27,48699951;27,39800072;27,30500031
I think you don't know how to search in a Binary Search Tree. You can do this by going to each node and can use recursion to do so.
In your search() you are taking Indicator as a parameter, but actually you need to take TreeNode because every node has a data of type Indicator which you can access.
In your search() you are calling the search() again and again with same parameters which will not give you results ever. Moreover, you don't have a base case. That's not how recursion work. You will be getting a stackoverflowException(Hahaa, its funny because we are on StackOverFlow). Use this code instead:
public void search(string key)
{
searchHelper(key, root); // root node will be in Tree.java
}
public void searchHelper(string key, TreeNode current)
{
if(current == null)
{
System.out.println("\nCant find !");
return;
}
if(key.compareTo(current.idct.getICode()) < 0 )
searchHelper(key, current.left);
else if(key.compareTo(current.idct.getICode()) > 0)
searchHelper(key,current.right);
else
System.out.println("\n"+current.idct + "Found \n");
}

Why is my constructor not initializing a variable correctly?

So I am trying to read in a file and create an arralist of those objects. The number of objects within the file is what I want my numItems variable to be set to, but I am getting an error.
public class Warehouse
{
// instance variables (fields)
private final static int MAX = 60;
private ArrayList <Item> stock;
private int numItems;
// the constructor
public Warehouse()
{
stock = new ArrayList<Item>();
numItems = loadData();
}
public int loadData(File infile) throws IOException
{
Scanner in = new Scanner (infile);
int number = 0;
while(in.hasNext())
{
String item = in.nextLine();
String [] items = item.split(" ");
String itemNum = items[0];
String itemName = items[1];
int onHand = Integer.parseInt(items[2]);
int committed = Integer.parseInt(items[3]);
int onOrder = Integer.parseInt(items[4]);
double price = Double.parseDouble(items[5]);
int reOrderPt = Integer.parseInt(items[6]);
int econOrder = Integer.parseInt(items[7]);
stock.add(number, new Item(itemNum, itemName, onHand, committed, onOrder, price, reOrderPt, econOrder));
number++;
}
return number;
}
Here is my main where I am reading the file and passing it into the loadData method:
public static void main(String args[]) throws IOException
{
// complete the main by adding the necessary variables and statements
int choice;
Scanner kb = new Scanner(System.in);
Warehouse inStock = new Warehouse();
String number = "";
int amount = 0;
File infile = new File("inventory.txt");
inStock.loadData(infile);
You're getting an error because loadData() expects a File argument and you're not passing any.
Why would you need to keep track of the number of items when you can just call ArrayList.size()?

Arrays of Object test but not getting any output

I would like some guidance on this particular code that I am testing but currently it is not printing out anything and on top of that I feel as if it isn't reading the text file at all. It seems to finish right away with no errors and I only get prompted that "build is successful."
The assignment is to read from a data text file that list 20 lines of student information, each line is comprised of first name, last name, and their grade all seperated by spaces. I am put to it into an array and output their information, but for now I am testing to see if it will output the first name before I proceed.
public class studentClass {
private String studentFName, studentLName;
private int testScore;
private char grade;
//constructor
public studentClass(String stuFName, String stuLName, int stuTestScore){
studentFName = stuFName;
studentLName = stuLName;
testScore = stuTestScore;
}
public String getStudentFName(){
return studentFName;
}
public String getStudentLName(){
return studentLName;
}
public int getTestScore(){
return testScore;
}
public char getGrade(){
return grade;
}
public void setStudentFName(String f){
studentFName = f;
}
public void setStudentLName(String l){
studentLName = l;
}
public void setTestScore(int t){
if (t>=0 && t<=100){
testScore = t;
}
}
public void setGrade(char g){
grade = g;
}
}
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
for(int i = 0; i>studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
public static studentClass[] readStudentData(studentClass[] studentObject)throws IOException{
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String lines = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((lines = br.readLine()) != null){
String stuArray[] = lines.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
return studentObject;
}
You need to actually call the method to read in the data. Try the following (note I didn't handle the Exception. I leave that as an exercise to you)
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
//NOTE I CHANGED THE '>' TO '<'
for(int i = 0; i < studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
//Note that I changed the return type to void
public static void readStudentData(studentClass[] studentObject)throws IOException{
//Your code here
You'll see I changed your readStudentData to return void since you're passing the array into the method you don't need to return it. You'll need to remove the return at the end of it.
You could also leave it as a method returning a studentClass[] and have no parameters. Instead, create the studentClass array inside readStudentData. I would recommend that approach because it removes the need to create and pass the array, which complicates your main method.

How to fix a loop for a heap structure

The code compiles but when you run it an error message occurs that gives a null pointer exception. As SEEN in the bottom. the code is supposed to read text from a txt file that is inputted in the program and then create a new txt file with the content of the first txt file sorted by years of service. However, i keep receiving that error message. Any help would be greatly appreciated. I added the error message at the bottom thank you to everyone who is helping your time and effort is greatly appreciated :)
(25 points)Define a Java class called Employee. The class has data members
and accompanying accessor and mutator methods for each of the following six data items. (This involves creating the file Employee.java.)
id (string)
name (string)
salary (double)
department (string)
position (string)
years of service (integer)
(25 points)Create a text (data) file containing data for at least five different
employees (objects). Let each data item sit on its own line in
the text file. For example, the first six lines of the file might look like:
086244
Sally L. Smith
100000.00
Accounting
Manager
7
(50 points)‘Heap’ is a tree-based data-structure that satisfies the heap property. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node.
By having a heap (or an array that satisfies the heap property), it would be more efficient (generally faster) to perform important tasks on the array such as finding the maximum element in the array (and removing it) and sorting the array.
In this assignment, you will have to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”
Heapsort code:
public class HeapSort
{
//heap sort method
public static <Employee extends Comparable<Employee>> void heapSort(Employee[] list)
{
//create a Heap of integers
Heap<Employee> heap = new Heap<>();
//add elements to the heap
for (int i = 0; i< list.length; i++)
heap.add(list[i]);
//remove elements from the heap
for(int i = list.length - 1; i >= 0; i--)
list[i] = heap.remove();
}
}
Heap code:
import java.util.ArrayList;
public class Heap<Employee extends Comparable<Employee>>
{
private ArrayList<Employee> list = new ArrayList<>();
public Heap(){}
public Heap(Employee[] objects)
{
for(int i = 0; i < objects.length; i++)
add(objects[i]);
}
public void add(Employee newObject)
{
list.add(newObject);
int currentIndex = list.size() - 1;
while(currentIndex > 0)
{
int parentIndex = (currentIndex -1)/2;
if(list.get(currentIndex).compareTo(list.get(parentIndex)) > 0)
{
Employee temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
}
else
break;
currentIndex = parentIndex;
}
}
public Employee remove()
{
if(list.size() == 0) return null;
Employee removeObject = list.get(0);
list.set(0, list.get(list.size() -1));
list.remove(list.size() -1);
int currentIndex = 0;
while(currentIndex < list.size())
{
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
if(leftChildIndex >= list.size()) break;
int maxIndex = leftChildIndex;
if(rightChildIndex < list.size())
{
if(list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
maxIndex = rightChildIndex;
}
if(list.get(currentIndex).compareTo(list.get(maxIndex)) < 0)
{
Employee temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
}
else
break;
}
return removeObject;
}
public int getSize()
{
return list.size();
}
public void print()
{
for (int i = 0; i <= getSize()-1; i++)
{
System.out.print("Index: " + i + " Data: " + list.get(i));
System.out.println();
}
}
}
Employee Object Class:
public class Employee implements Comparable<Employee>
{
private String id;
private String name;
private double salary;
private String department;
private String position;
private int yos;
public Employee(String id, String name, double salary,String department,String position,int yos)
{
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
this.position = position;
this.yos = yos;
}
public void setid(String id)
{
this.id = id;
}
public void setname(String name)
{
this.name = name;
}
public void setsalary(double salary)
{
this.salary = salary;
}
public void setdepartment(String department)
{
this.department = department;
}
public void setposition(String position)
{
this.position = position;
}
public void setyos(int yos)
{
this.yos = yos;
}
public String getid()
{
return id;
}
public String getname()
{
return name;
}
public double getsalary()
{
return salary;
}
public String getdepartment()
{
return department;
}
public String getposition()
{
return position;
}
public int getyos()
{
return yos;
}
public int compareTo(Employee emp)
{
return (this.yos - emp.yos);
}
public String toString()
{
return "ID=" + this.id+ ", name=" + this.name+ ", salary= $" + this.salary+ ", department:" + this.department+ ", postion:" + this.position+ ",yos= $" + this.yos + "]\n";
}
}
Demo code:
import java.util.*;
import java.io.*;
public class EmployeeDemo
{
public static void main(String[] args)throws IOException
{
Employee[] list = new Employee[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the text file: ");
String fileName = keyboard.nextLine();
File myFile = new File(fileName);
Scanner inputFile = new Scanner(myFile);
//Read all of the values from the file
//and calculate their total
//Read a value from the file
String id = inputFile.nextLine();
String name = inputFile.nextLine();
double salary = inputFile.nextDouble();
String clear = inputFile.nextLine();
String department = inputFile.nextLine();
String position = inputFile.nextLine();
int yrService = inputFile.nextInt();
String llear = inputFile.nextLine();
list[0] = new Employee(id,name,salary,department,position,yrService);
//close the file
// File o = new File("SortedEmployee.txt");
//o.createNewFile();
System.out.println("Enter the file name to be transfered to: ");
String filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);//dont need the top
//HeapSort<Employee> h = new heapSort<Employee>(Employee);
HeapSort.heapSort(list);
//Display the sum of the numbers
while(inputFile.hasNext())//this loop is wrong too
{
outputFile.println(list[0].toString());
}
outputFile.close();
inputFile.close();
System.out.print("File Sorted and Transferred");
}
}
here is the error message i am receiving:
Please enter the text file:
C:\Users\jose385\Desktop\Employee.txt
Enter the file name to be transfered to:
green
Exception in thread "main" java.lang.NullPointerException
at Heap.add(Heap.java:22)
at HeapSort.heapSort(HeapSort.java:13)
at EmployeeDemo.main(EmployeeDemo.java:50)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You make the List have a size of 5
Employee[] list = new Employee[5];
but only add one element
list[0] = new Employee(id,name,salary,department,position,yrService);
Actually what is the point of only sorting one element
Also try to follow a tutorial on the correct way to implement Comparable

Class object array can get only one object

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.

Categories