Having an object, remember the following object of this kind

Right, vaguely how this topic could be, let me start by admitting that this is a homework-related question. So if you have any funny vendetta against these questions, be forewarned.

I sat with him for hours though, and I am embarrassed not to "get him".

So I was hoping that some of you can show me what I am missing.

I have to create a class that stores a variable and remembers the next object of that class.

The following is my main class:

public class SticksAndStones {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String response = "n";
    Stick currentStick = null;
    int numberOfSticks = 0;

    while (response.equals("n")) {

        System.out.println("What diameter should the stick have?");
        response = Integer.toString(scan.nextInt());

        currentStick = new Stick(Integer.parseInt(response), currentStick);
        numberOfSticks++;

        System.out.println("Are you done adding sticks? ('n' or 'y')");
        response = scan.next();

        while (!response.equals("y") && !response.equals("n")) {
            System.out.println("Please type 'y' for yes, or 'n' for no.");
            response = scan.next();
        }
    }

    for (int i = 0; i < numberOfSticks; i++) {
        System.out.println(currentStick.getDiameter());
        currentStick = currentStick.getNext();
    }

}
}

      

The My Stick class looks like this:

public class Stick {

int diameter;
Stick stick;

public Stick(int diameter, Stick stick) {

    this.diameter = diameter;
    this.stick = stick;

}

public int getDiameter() {
    return diameter;
}

public Stick getNextStick() {
    return stick;
}

      

Now, as you can see, my class seems to be able to remember the previous stick, but not the next one anyway.

The reason this is a problem is because at the bottom of my SticksAndStones class I am trying to print the diameters of each stick, but they do not come out in the correct order. In other words, the first stick appears last, and the last stick appears first.

What I don't need. I need them to go the other way. Insert first as stick out first.

Our only limitation in this task is that we cannot use arrays, lists, tables, or databases of any shape.

Am I missing something incredibly simple?

PS: Would use the "homework" tag, but it doesn't allow that.

UPDATE

New SticksAndStones class:

import java.util.Scanner;

public class SticksAndStones {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String response = "n";
    int numberOfSticks = 0;

    Stick firstStick = null;
    Stick currentStick = null;
    ;
    Stick prevStick = null;

    while (response.equals("n")) {

        System.out.println("What diameter should the stick have?");
        response = Integer.toString(scan.nextInt());

        if (firstStick == null) {
            firstStick = new Stick(Integer.parseInt(response));
            prevStick = firstStick;
        } else {
            currentStick = new Stick(Integer.parseInt(response));
            prevStick.setNextStick(currentStick);
            prevStick = currentStick;
        }

        numberOfSticks++;

        System.out.println("Are you done adding sticks? ('n' or 'y')");
        response = scan.next();

        while (!response.equals("y") && !response.equals("n")) {
            System.out.println("Please type 'y' for yes, or 'n' for no.");
            response = scan.next();
        }
    }

    currentStick = firstStick;
    for (int i = 0; i < numberOfSticks; i++) {
        System.out.println(currentStick.getDiameter());
        currentStick = currentStick.getNextStick();
    }

}
}

      

And my Sticks class:

public class Stick {

int diameter;
Stick stick;
Stick nextStick;

public Stick(int diameter, Stick stick) {

    this.diameter = diameter;
    this.stick = stick;

}

public Stick(int diameter) {
    this.diameter = diameter;
}

public int getDiameter() {
    return diameter;
}

public Stick getNextStick() {
    return stick;
}

public void setNextStick(Stick nextStick) {
    this.nextStick = nextStick;
}
}

      

Smile and hug to whoever can tell me why I am finding NullPointerException.

+3


source to share


4 answers


A little refactoring goes a long way:

Since it is impossible to know the construction time, which means next

Stick, the constructor should not take it as a parameter or the smallest value makes it possible to create an object withoutnextStick

public Stick(int diameter) {
    this.diameter = diameter;
}

      

Before you start the loop to add Sticks, you keep 3 links:

Stick firstStick = null;
Stick currentStick;
Stick prevStick = null;

      

And inside yours, while loop

after you ask Diameter, you check if an initial stick was specified or if you are constantly adding sticks ...

if (firstStick == null) {
    firstStick = new Stick(Integer.parseInt(response));
    prevStick = firstStick;                
} else {
    currentStick = new Stick(Integer.parseInt(response));
    prevStick.setNextStick(currentStick);
    prevStick = currentStick;
}

      



Outside of your loop when you print the information you set currentStick

points to firstStick

and loop as always

currentStick = firstStick;
for (int i = 0; i < numberOfSticks; i++) {
    System.out.println(currentStick.getDiameter());
    currentStick = currentStick.getNextStick();
}

      

Update

As per your change in class Stick

It should look like this:

public class Stick {

    int diameter;
    Stick stick;

    public Stick(int diameter) {
        this.diameter = diameter;
    }

    public int getDiameter() {
        return diameter;
    }

    public Stick getNextStick() {
        return stick;
    }

    public void setNextStick(Stick stick) {
        this.stick = stick;
    }
}

      

+1


source


Well, obviously it Stick

can "remember" the next stick when it is first created, because there is no other stick yet. But if the only constructor Stick

takes the previous finger as an argument, then while it's rather ugly, it can modify the previous stick to have a reference to the new one:

public Stick(int diameter, Stick previousStick) {
    this.diameter = diameter;
    this.previous = previousStick;
    previousStick.next = this;
}

      

Of course, this assumes one new and one renamed field in the Stick class.



Better would be to add a link ahead after creating a new one Stick

, so that the constructor Stick

won't change its arguments:

public Stick(int diameter, Stick previousStick) {
    this.diameter = diameter;
    this.previous = previousStick;
}

// ... main() ...
    Stick newStick = new Stick(Integer.parseInt(response), currentStick);

    currentStick.setNext(newStick);

      

Also, if you want to be able to move the linked list (which you create) in a forward direction, you need to store a link to the first somewhere Stick

. If you don't need to move the list backwards, you can omit tracking this reference (in which case the constructor Stick

shouldn't take Stick

as a parameter). I'll leave the rest to you.

+1


source


Another option that avoids adding a second reference so that each Stick remembers the previous one is to write a recursive method that traverses after traversing the chained chain:

public static void printSticks(Stick s) {
  if (s != null) {
    printSticks(s.getNextStick());
    System.out.println(s.getDiameter());
  }
}

      

This approach is not suitable for a very long list as it is error prone, but this is an example of how you can use recursive algorithms to work with the constraints of a data structure that you are stuck with.

+1


source


You might ask your class about previous and subsequent sticks.

public class Stick {
    private int diameter;
    private Stick previousStick;
    private Stick nextStick;

    public Stick(int diameter, Stick previousStick, Stick nextStick) {
        setDiameter(diameter);
        setPreviousStick(previousStick);
        setNextStick(nextStick);
    }

    //getters and setters
}

      

Then in your main method you will need to set them appropriately. This is where you have to "do your homework". Below is some help. Think about how to use it.

Stick lastStick;
Stick currentStick;

lastStick = currentStick;
currentStick = new Stick(diameter, lastStick, null);
lastStick.setNextStick(currentStick);

      

0


source







All Articles