Reputation: 129
So I'm trying to make a linked list of characters, first I'm going to point out that we're not allowed to use the built in methods for linked lists in java already. When I add the characters and then try to display them, it just gives me a list of numbers. Why is this happening?
class Node{
int data;
Node next;
public Node(Character x){
data = x; next = null;
}
public Node next(){return next;}
public void setNext(Node p){
next = p;
}
public void set(Character x){data = x;}
public int data(){return data;}
}
class Reader{
Node head = null;//empty list
public void add(Character x){ //add at head
Node nw = new Node(x);
nw.setNext(head);
head = nw;
}
public void display(){
Node k = head;
System.out.print('[');
while(k!=null){
if(k.next!=null)
System.out.print(k.data()+",");
else
System.out.print(k.data());
k=k.next();
}
System.out.print(']');
}
}
class assignment9{
public static void main(String[]args){
Reader r1 = new Reader();
r1.add('r');
r1.add('e');
r1.add('l');
r1.add('l');
r1.add('o');
r1.display();
}
}
Upvotes: 0
Views: 204
Reputation: 54084
Just cast to char
System.out.print((char)k.data()+",");
and
System.out.print((char)k.data());
You can use int
here as you have, but it is best to use the most appropriate type for each variable in your case char
Upvotes: 0
Reputation: 4102
you are printing out ints in your call to data(). if you want this represented as a Character, make sure that data is of type Character.
Upvotes: 0
Reputation: 9334
Inside your Node, don't store the data as an int if you want it represented as a char. An int is a numeric type, a char is a character type.
Upvotes: 1