Object array with variable from another class - java

Worksheet Question:
The question said to declare an array of 5 objects of the class Node in the main Class - I managed to this as shown below
But then the question continues populate the array by objects with seqNo values assigned to 1,2,3,4,5 respectively. Then traverse the array and print the list of its object using method show()
I have an error when I am trying to show the array to the user.
I am trying to display the array by this line of code:
nodObj[].show();
Below I have all the code except the Person class. Does someone have any idea if I should do a loop. When i tried if loop I got an error too. I have the display part code wrong I can't figure out what to change
My AnyClass
import java.util.Scanner;
public class AnyClass
{
public int seqNo;
/* -----------------Constructor------------*/
public AnyClass(int num)
{
seqNo = num; //initializing
}
//empty constructor
public AnyClass()
{
}
//intialized
public void initializeseqNo(int seqNum)
{
seqNum = seqNo;
}
/*-----Mehtods*/
public String getData()
{return "Sequence number " +seqNo+".";
}
public String getKey()
{
return String.valueOf(seqNo); //for search by seqNo
}
public void editData() //empty method to be overriden by future subcclasses
{
}
public void edit(){
Scanner sc = new Scanner(System.in);
seqNo = sc.nextInt();//next line for String
}
} //end of AnyClass
My Node class
public class Node
{
public AnyClass obj;
public Node(AnyClass newObj)
{
obj = newObj;
}
public void show()
{
System.out.println(obj.getData());
}
}
MainProg
class MainProg{
public static void main (String[] args) {
//-----------Construction of objects---------
Person head = new Person ("Gatt", 21445667);
Person clerk = new Person();
clerk.name = "Delia";
System.out.println ("Data of a new Head: " +head.getData());
AnyClass ac1 = new AnyClass(51);
AnyClass ac2 = new AnyClass(52);
AnyClass ac3 = new AnyClass(53);
ac1.getData();
ac2.getData();
ac3.getData();
//edit value of ac1
ac1.edit();
//print all values again
ac1.getData();
ac2.getData();
ac3.getData();
Node n = new Node(new AnyClass(3));
//print values
n.show();
Node nodObj[] = new Node[5]; //allocating memory to array
//populate array
nodObj[0] = new Node(new AnyClass(1));
nodObj[1] = new Node(new AnyClass(2));
nodObj[2] = new Node(new AnyClass(3));
nodObj[3] = new Node(new AnyClass(4));
nodObj[4] = new Node(new AnyClass(5));
//printing array
nodObj[].show(); //ERROR THIS IS WRONG!
}//end of Main()
}//end of program class

Below I have all the code except the Person class. Does someone have
any idea if I should do a loop. When i tried if loop I got an error
too. I have the display part code wrong I can't figure out what to
change
Yes, you need to loop over the array. At this level of instruction you should use a for or foreach loop.
for (int index = 0; index < nodObj.length; index++) {
nodObj[index].show();
}
Or
for (Node node : nodObj) {
node.show();
}

Related

Java Number Randomizer is getting null as output

In this program I've created a class called ArrayExample and created a random number to fill its elements and a toString() method with it. Why am I getting null as my output? The code has no errors from what it seems like. :
public class arran {
public static void main(String[] args) {
ArrayExample[] no1 = new ArrayExample[5];
System.out.println(Arrays.toString(no1));
}
public class ArrayExample {
int[] array;
ArrayExample(int len) {
array = new int[len];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 100);
}
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(array.length);
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
return sb.toString();
}
}
}
You're creating ArrayExample[5], which is an array of five ArrayExample objects, and not a single ArrayExample with a constructor argument of 5. It looks like your intent was to invoke the constructor ArrayExample(int len), but it's never called.
Try this, instead:
public static void main(String[] args) {
ArrayExample no1 = new ArrayExample(5); // Invokes the constructor you wrote
System.out.println(no1.toString()); // Uses the toString method your wrote
}
Make your inner class static so it can be accessed by your main method:
public static class ArrayExample {
And fix your .toString() method:
public String toString() {
return Arrays.toString(array);
}
The problem is in this code:
ArrayExample[] no1 = new ArrayExample[5];
System.out.println(Arrays.toString(no1));
This declares an array of a certain type (ArrayExample), and a certain length (5), but it doesn't do anything else. That first line results in a variable reference no1 containing five null values. That's what you see when you print it out.
[null, null, null, null, null]
Here's another example, but using Object to highlight that the code isn't doing anything other than creating an empty array and printing the null values.
Object[] no2 = new Object[5];
System.out.println(Arrays.toString(no2));
This code has the same output:
[null, null, null, null, null]
Here is code that will initialize the array (like you already were doing), then create a new instance of ArrayExample and save it at each array element. (I also moved ArrayExample out of the main class definition so that it compiles).
public class Example {
public static void main(String[] args) {
ArrayExample[] no1 = new ArrayExample[5];
no1[0] = new ArrayExample(10);
no1[1] = new ArrayExample(10);
no1[2] = new ArrayExample(10);
no1[3] = new ArrayExample(10);
no1[4] = new ArrayExample(10);
System.out.println(Arrays.toString(no1));
}
}
class ArrayExample {
// use same class contents as your original post
}
Here is output from running this updated code:
[6474373150570442153, 27524825597078735826, 58127219204026904839, 90611080549351937198, 6503557163540938849]
Another option for setting your array contents would be using this one-liner:
Arrays.setAll(no1, k -> new ArrayExample(10));

How to display Fibonacci numbers using a Linked list in Java

I have created a class using linked list to display 20 Fibonacci numbers. Here is my code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList(LinkedList<Integer> FibonacciLinkList) {
this.fibonacciList = FibonacciLinkList;
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
LinkedList fibonacciList = new LinkedList();
fibonacciList.display(); //This is where the error is
}
}
The problem I am having is displaying the Fibonacci numbers on the console.
I have tried to do this by using a display method but it hasn't really worked for me. I have done a lot of searching online and on SO and have tried them but they have not worked for me. It would be appreciated if you could fix my code so that it does work.
I am new to linked list and this is the first time I am coding a linked list myself and I feel that a solution to this problem will help me understand linked lists better.
As I mentioned, LinkedList is not an instance of FibonacciLinkedList, and it does not possess the display() method. Attempting to invoke it on the LinkedList object will lead to failure to compile.
The sum() method is not invoked nor does it actually do anything. That is, it does not assign anything to the fibonacciList you have.
I would recommend that you extend the LinkedList class and generate the items on instantiation. Then, using the default toString() you can display to console. After all, the class is simply an extension of the LinkedList data structure to store Fibonacci numbers up to 20.
As you extend LinkedList, you inherit the AbstractCollection.toString() method for which the "string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]")."
public class FibonacciLinkedList extends LinkedList<Integer> {
public FibonacciLinkedList(int n){
int a = 0, b = 0, c = 1;
for(int i = 1; i <= n; i++) {
a = b;
b = c;
c = a + b;
this.add(c);
}
}
public void display() {
System.out.println(this.toString());
}
public static void main(String[] args) {
FibonacciLinkedList list = new FibonacciLinkedList(20);
list.display();
}
}
I fixed your code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList() {
this.fibonacciList = new LinkedList<Integer>();
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
fibonacciList.add(a);
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
FibonacciLinkList fibonacciList = new FibonacciLinkList();
fibonacciList.sum();
fibonacciList.display();
}
}
Try this.
There is several points that you need to take care :
sum() is never called.
the look in sum() does not change fibonacciList, it only uses local variables and does nothing else with it.
display() is NOT a LinkedList function, so it will likely not work. And even if it were working, it will likely not display what you expect : you need to loop through the list and print each value.
an other fibonacciList is created in the main function, so the display (if it was working) would show the content of this local list and not the global one.

reverse a stack and concatenate a popped stack

I'm trying to push any array list to a stack in reverse then concatenate a popped stacked. I getting the information from a file then storing it into an array List. Then i pushed the array List into a stack. now when i print the stack out its just printing the array List how can i pop the stack and concatenate it? here is my code so far
public static LinkedListStack myStack = new LinkedListStack();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
song.add(line = inFile.next());
}
for(int i = 0; i < song.size(); i++)
{
myStack.push1(song);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
if(!myStack.empty())
{
System.out.println(myStack.pop1());
} else
{
System.out.println("Sorry stack is empty");
}
}
output looks like this now :[Mary, had, a, little, lamb, Whose, fleece, was, white, as, snow, Everywhere, that, Mary, went, The, lamb, was, sure, to, go]
I'm trying to get it to look like this:
lamb little a had Mary
snow as white was fleece Whose
went Mary that Everywhere
go to sure was lamb The
i have made a custom class for the push and pop
{
private Node first;
/**
Constructs an empty stack.
*/
public LinkedListStack()
{
first = null;
}
/**
Adds an element to the top of the stack.
#param element the element to add
*/
public void push1(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
/**
Removes the element from the top of the stack.
#return the removed element
*/
public Object pop1()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}
/**
Checks whether this stack is empty.
#return true if the stack is empty
*/
public boolean empty()
{
return first == null;
}
class Node
{
public Object data;
public Node next;
}
}
I fixed the problems in your code. Here is the working version along with some comments. This assumes the sentences in the file are separated by new lines and the words are separated by white spaces.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneralTest {
//You want the same ordering for sentences. This collection
//therefore should be a list (or a queue)
//I have not changed the name so you can see how it makes a
//difference
public static List<LinkedListStack> myStack = new ArrayList<>();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
//Here you need to use nextLine() instead of next()
song.add(inFile.nextLine());
}
//This loop is the main location your original code goes wrong
//You need to create a stack for each sentence and add it to the
//list. myStack will hold a list of stacks after this loop is done
for(int i = 0; i < song.size(); i++)
{
String songString = (String) song.get(i);
String[] sga = songString.split(" ");
LinkedListStack rowStack = new LinkedListStack();
for(int j=0; j < sga.length; j++) rowStack.push1(sga[j]);
myStack.add(rowStack);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
//To get all values in a collection you need to
//loop over it. A single if will not work
for(LinkedListStack rs : myStack)
{
//Each entry in the list is a LinkedListStack
//So you can pop them and print the results with
//appropriate separators
while(!rs.empty())
System.out.print(rs.pop1() + " ");
System.out.println();
}
}
}
Now, your code has many other problems. For example, you really should use generics when you create a collection class.
The main problem with your code is that to produce the output you have described, you will need a queue of stacks. I have implemented the concept using ArrayList to show the source of the problem. But if you want to learn data structures (or if this is a homework problem), then you should try implementing and using a queue as well.

Getting size and comparing attribute value from ArrayList in other class

I am trying to create a method which creates a result for a athlete in a competition. I have an ArrayList with the athletes in another class and now I want this method to be able to find the size of the ArrayList and also compare one int attribute of every Athlete with the input number. This is what I have so far, Im really stuck. So my quetions to you are: How do I get my for loop to see the size of the ArrayList athletes? and what is a proper way to check whether or not the input has a matching athlete in the ArrayList(I want it to print out if there is no match)? Thank you
public class ResultList {
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
public ResultList() {
ArrayList<Athlete> temp = new AthleteList().getArrayList();
}
void addResult() {
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
for (int i = 0; i < athletes.size(); i++) {
}
}
}
Other class with the Athlete ArrayList:
public class AthleteList {
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
public AthleteList () {
}
public ArrayList<Athlete> getArrayList() {
return athletes;
}
You should create a variable that points to the AthleteList class. Then you can see that in the addResult method you just get the ArrayList from the AthleteList and call size() on it and iterate over the Athletes and check the completionNumber(You didn't post the Athlete class so I'm assuming there is a completionNumber property). I create a matched variable to hold on to the matched Athlete. After the loop I check to see if one matched and print out the result.
Hope this helps.
public class ResultList
{
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
AthleteList athleteList;
public ResultList()
{
athleteList = new AthleteList();
}
void addResult()
{
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
Athlete matched = null;
List<Athlete> athletes = athleteList.getArrayList();
for(int i = 0; i < athletes.size(); i++)
{
if(athlete.completionNumber == completionNumber)
{
//you found a match!!
matched = athlete;
}
}
if(matched == null)
{
System.out.println("No Match Found for " + completionNumber);
}
else
{
System.out.println("Found match: " + matched.toString());
}
}
}
NOTE:
Not sure you need the AthleteList class. It's just holding an ArrayList. If that's all that class will ever do then I suggest you just using an ArrayList. It will make your code cleaner.

Null pointer exception for Array of Objects

I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.

Categories