toString, Nullpointerexception - java

I'm getting a Nullpointerexception when trying to get the trees name from the arraylist. I've tested just getting the name alone but i'm still getting this error. All i want to do is know which Equipment is cutting which tree.
public class TreeTester {
public static void main(String[] args) {
Tree trees = new Tree("Trees");
Tree tree1 = new Tree("Ash Tree");
trees.addTree(tree1);
Tree Class
public Class Tree{
private ArrayList<Tree> theTrees;
private String treeName;
//Forgot these
Tree(String trees //There are more but not relevent) {
theTrees = new ArrayList<Tree>();
}
Tree(String treeName){
this.treeName = treeName;
}
//
public boolean addTree(Tree newTree){
theTrees.add(newTree);
return true;
}
#Override
public String toString(){
String s = getTreeName();
return s;
}
private String getTreeName() {
return this.treeName; }
}
//------------------Shortened for ease--------------------------//
Just imagine the missing vars and contructor
public Class Equipment{
private Tree TreeDetails;
#Override
public String toString(){
String s = "Using " + getEqupiment(); + "to cut " + setCutTree()
}
public boolean setCutTree(){
this.treename = treename.toString(); //Nullpointer issue here
return this.treecut = true;
//getEquipment works fine
}
}

You need to intialize the theTrees ArrayList
public class Tree {
private ArrayList<Tree> theTrees = new ArrayList<Tree>();
You have also left out the one argument constructor of Tree that you are using in the main method. Since you are getting a NullPointerException even when accessing the name I assume this constructor does not initialize the treeName either.
With the constructor the class should look something like this:
public class Tree {
private ArrayList<Tree> theTrees;
private String treeName;
public Tree(String treeName) {
this.treeName = treeName;
this.theTrees = new ArrayList<Tree>();
}
...

Related

Integrate with a jar

just a quick question. I have a jar file and I want to integrate it within my project. The decompiled version of the jar file looks like this:
public abstract class SinglyLinkedList
protected SinglyLinkedList.Item head;
public void addFront(String s) {
if (head == null) {
head = new SinglyLinkedList.Item(s);
}
else {
SinglyLinkedList.Item insert = new SinglyLinkedList.Item(s);
next = head;
head = insert;
}
}
public void add(String[] array) { String[] arrayOfString;
int j = (arrayOfString = array).length; for (int i = 0; i < j; i++)
{ String s = arrayOfString[i];
addFront(s);
}
}
public String toString()
{
if (head == null) {
return "empty list";
}
String s = "";
for (SinglyLinkedList.Item helper = head; next != null; helper = next) {
s = String.valueOf(s) + value + ", ";
s = String.valueOf(s) + value;
return s;
}
public abstract void sort();
protected class Item
{
public Item next;
public String value;
public Item(String value) {
this.value = value;
}
}
}
Now I want to create a new linked list in my other class, but this doesnt work:
private SinglyLinkedList linkedlist;
public SelectionSortableList(){
this.linkedlist = new SinglyLinkedList();
}
He cannot instantiate it. Can please somebody tell me why he don't want to instantiate it? Thank you in beforehand.
public abstract class SinglyLinkedList
Because this is an abstract class. abstract classes cannot be instantiated.
You need to extend it and implement the following abstract method:
public abstract void sort();
Once you extend the class all the non-private method will be directly accessible into your super class.
Your class should be like this:
class SelectionSortableList extends SinglyLinkedList {
#Override
public void sort() {
// provide you implementation here.
}
}

Why does this not print the String inside the object?

This program is used for a flash card application. My constructor is using a linked list, but the problem is that when I use a method that list the cards inside a specific box it is not printing the desired result. The system should print "Ryan Hardin". Instead it is printing "Box$NoteCard#68e86f41". Can someone explain why this is happening and what I can do to fix this? I have also attached both my box and note card classes.
import java.util.LinkedList;
import java.util.ListIterator;
public class Box {
public LinkedList<NoteCard> data;
public Box() {
this.data = new LinkedList<NoteCard>();
}
public Box addCard(NoteCard a) {
Box one = this;
one.data.add(a);
return one;
}
public static void listBox(Box a, int index){
ListIterator itr = a.data.listIterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
public static void main(String[] args) {
NoteCard test = new NoteCard("Ryan", "Hardin");
Box box1 = new Box();
box1.addCard(test);
listBox(box1,0);
}
}
This is my NoteCard Class
public class NoteCard {
public static String challenge;
public static String response;
public NoteCard(String front, String back) {
double a = Math.random();
if (a > 0.5) {
challenge = front;
} else
challenge = back;
if (a < 0.5) {
response = front;
} else
response = back;
}
public static String getChallenge(NoteCard a) {
String chal = a.challenge;
return chal;
}
public static String getResponse(NoteCard a) {
String resp = response;
return resp;
}
public static void main(String[] args) {
NoteCard test = new NoteCard("Ryan", "Hardin");
System.out.println("The challenge: " + getChallenge(test));
System.out.println("The response: " + getResponse(test));
}
}
Try to override the method toString() in your class NoteCard.
#Override
public String toString()
{
//Format your NoteCard class as an String
return noteCardAsString;
}
In First place you are making too much use of static keyword. I am not sure whether you need that. Anyways create two instance variable front and back and assign value to it in constructor of NoteCard class, Also implement toString method
public class NoteCard {
public static String challenge;
public static String response;
public String front;
public String back;
public NoteCard(String front, String back) {
//your code
this.front = front;
this.back = back;
}
#Override
public String toString()
{
//return "The challenge:" + challenge + " " + "The response: " + response;
return "The Front:" + front + " " + "The Back: " + back;
}
Note: Since the instance method toString() is implicitly inherited
from Object, declaring a method toString() as static in a sub type
causes a compile-time error SO DON'T MAKE THIS METHOD STATIC

Can't print objects stored in HashMap?

I'm working on an assignment for my java class, and we just started learning about HashMaps and we have this assignment where we create enumerated data and store it in a hashmap to print out later. What I can seem to figure out is to be able to print the elements of the HashMap. Here is my project so far:
public class Driver <enumeration>
{
private static HashMap<String, State> stateList = new HashMap<String, State>();
public static void main(String args[]) throws IOException
{
stateList.put("1", State.CA);
stateList.put("2", State.FL);
stateList.put("3", State.ME);
stateList.put("4", State.OK);
stateList.put("5", State.TX);
for(State value : stateList.values())
{
System.out.println(value);
}
}
}
public enum State
{
CA(new StateInfo("Sacramento", 38802500)), FL(new StateInfo("Tallahassee", 19893297)),
ME(new StateInfo("Augusta", 1330089)), OK(new StateInfo("Oklahoma City", 3878051)),
TX(new StateInfo(" Austin", 26956958));
private StateInfo info;
private State(StateInfo info)
{
this.info = info;
}
public StateInfo getInfo()
{
return info;
}
public String toString()
{
return "";
}
}
public class StateInfo
{
private String capital;
private int population;
public StateInfo(String capital, int population)
{
this.capital = capital;
this.population = population;
}
public String getCapital()
{
return capital.toString();
}
public int getPopulation()
{
return population;
}
public String toString()
{
return "";
}
}
Now when I try to run the program, it just terminates without even as much as a reference number for the state objects I'm trying to print. What I think is wrong is in the StateInfo class so I tried changing some things but to no prevail. Can anyone tell me if my suspensions are correct, or am I overlooking something?
You have overridden the toString() method in the State class:
public String toString()
{
return "";
}
Therefore you get no output at all as for every value the toString() method is called in your loop:
for(State value : stateList.values())
{
System.out.println(value);
}
To be more precise: You should get 5 empty lines.
Remove the toString()method in order to use Java's default toString() implementation which returns the classname+hashCode() or make it return e.g. "Capital: " + info.getCapital().

Object-oriented design for comment subject object

I'm trying to figure out the best way to design a class, which encapsulates JSON-derived comments. Each comment is targeted at a particular subject, either a file as a whole or a line of a file. Here's an example comment:
{
"text":"This is my favorite line!",
"path":"My file.txt",
"line":42
...
}
If the subject is a file as a whole, line is null.
I want the Comment class to have a subject() method, but I'm not sure the best way to design the CommentSubject class. Here's what I have so far:
import javax.json.JsonObject;
class Comment {
private final JsonObject json;
private final CommentSubject subject;
public JsonObject json() { return json; }
public CommentSubject subject() { return subject; }
public Comment(JsonObject json) {
...
this.json = json;
subject = json.isNull("line") ? new FileSubject(this) :
new LineSubject(this);
...
}
...
}
abstract class CommentSubject {
enum SubjectType {
FILE, LINE
}
public abstract SubjectType type();
public abstract String path();
protected abstract Comment comment();
}
class FileSubject extends CommentSubject {
private final Comment comment;
private final String path;
public FileSubject(Comment comment) {
this.comment = comment;
path = comment.json().getString("path");
}
public FileSubject(CommentSubject subject) {
this(subject.comment());
}
#Override public SubjectType type() { return SubjectType.FILE; }
#Override public String path() { return path; }
#Override protected Comment comment() { return comment; }
...
}
class LineSubject extends CommentSubject {
private final Comment comment;
private final String path;
private final int line;
public LineSubject(Comment comment) {
this.comment = comment;
path = comment.json().getString("path");
line = comment.json().getInt("line");
}
public LineSubject(CommentSubject subject) {
this(subject.comment());
}
#Override public SubjectType type() { return SubjectType.LINE; }
#Override public String path() { return path; }
#Override protected Comment comment() { return comment; }
public int line() { return line; }
...
}
Client code could look like this:
doSomething(CommentSubject subject) {
if (subject.type() == SubjectType.LINE) {
LineSubject line = new LineSubject(subject);
...
}
...
}
However, I don't like the fact that my current design requires a new LineSubject object in the client code: subject and line are identical in the example above, so the new object creation seems like a waste of space. Further, in order to pass a CommentSubject object to another CommentSubject constructor, as in the client code above, all subjects need to be backed by a comment accessible by the comment() method. I also don't know what I think about the SubjectType enum.
What I want is for Comment to have a subject() method and to be able to distinguish file and line subjects. Are there better designs out there?
If the only difference between a file comment and a line comment is that the file comment does not have a line number, you can fold the class hierarchy to a single class, and make the line number optional (i.e. returning an Integer rather than an int). This would let client programs distinguish between file and line comments, because file comments would return null for the line number:
public class CommentSubject {
private final Integer line;
private final String path;
private final String comment;
public String path() { return path; }
public Integer line() { return line; }
public Comment comment() { return comment; }
public static CommentSubject forFile(String p, String c) {
return new CommentSubject(p, null, c);
}
public static CommentSubject forLine(String p, int i, String c) {
return new CommentSubject(p, i, c);
}
private CommentSubject(String p, Integer i, String c) {
path = p;
line = i;
comment = c;
}
}
The client would be able to write something like this:
doSomething(CommentSubject subject) {
Integer optLine = subject.line();
if (optLine != null) {
int line = optLine.intValue();
...
}
...
}
If you prefer to avoid conditional dispatch in the client, you could take a visitor-like approach, and have the CommentSubject call back the processor of your comments, like this:
interface CommentProcessor {
void onFileComment(String path, String comment);
void onLineComment(String path, int line, String comment);
}
public class CommentSubject {
private final Integer line;
private final String path;
private final String comment;
public void process(CommentProcessor p) {
if (line != null) {
p.onLineComment(path, line.intValue(), comment);
} else {
p.onFileComment(path, comment);
}
}
public static CommentSubject forFile(String p, String c) {
return new CommentSubject(p, null, c);
}
public static CommentSubject forLine(String p, int i, String c) {
return new CommentSubject(p, i, c);
}
private CommentSubject(String p, Integer i, String c) {
path = p;
line = i;
comment = c;
}
}
Note how the comment, path, and line are hidden inside CommentSubject. The only way to access them now is to pass an instance of CommentProcessor, which would receive a callback for the appropriate type of CommentSubject.

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

Categories

Resources