Our teacher gave us a new task and somehow I am not able to figure out the problem.
There are 3 different java classes and I am only allowed to change the ToDoList class. There, I want to add a new List so that the main class is able to add new Items to my todo list. As you can see below, I tried to initialize a new list but that did not work.
Where is my mistake?
public class ToDoListEntry {
String task;
LocalDate date;
ToDoListEntry next;
public ToDoListEntry(LocalDate date, String task) {
this.task = task;
this.date = date;
}
}
Then comes the next where I tried to add an array but which did not work:
public class ToDoList {
ToDoListEntry first;
public ArrayList<ToDoListEntry> todolist;
public ToDoList (){
todolist = new ArrayList<ToDoListEntry>();
}
public void add(ToDoListEntry newTask) {
todolist.add(newTask);
}
public String print() {
String result = "";
if (first == null) {
result = "Empty list!\n";
} else {
ToDoListEntry pointer = first;
while (pointer != null) {
result += "Until " + pointer.date + " Task: "
+ pointer.task +"\n";
pointer = pointer.next;
}
}
System.out.println(result);
return result;
}
}
And in the end, the main class should supposed to create a new ToDo List and print it out (Note that I did not include the print() Method):
public static void main(String[] args) {
System.out.println("Test 00: Empty List");
ToDoList list2016 = new ToDoList();
list2016.print();
System.out.println("Test 01: add");
list2016.add(new ToDoListEntry(LocalDate.of(2016, 8, 15), "Do workout"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 6, 3), "Buy apples"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 10, 11), "Read Books"));
list2016.print();
When you add a new entry to the list, you don't set the next pointer of that entry. But in the print() method, you use the next pointer, but (if you don't set it somewhere else) it is still null. Try your add() method like this:
public void add(ToDoListEntry newTask) {
todolist.add(newTask);
if (todolist.size() >= 2) todolist.get(todolist.size()-2).next = newTask;
}
But are you sure you can use an ArrayList here? I get the impression that you have to implement a linked list. In this case the code would look like this:
class ToDoListEntry {
String task;
LocalDate date;
ToDoListEntry next;
public ToDoListEntry(LocalDate date, String task) {
this.task = task;
this.date = date;
}
}
public class ToDoList {
ToDoListEntry first;
int size;
public ToDoList (){
first = null;
size = 0;
}
public void add(ToDoListEntry newTask) {
if (first == null){
first = newTask;
}else{
ToDoListEntry pointer = first;
while (pointer.next != null){
pointer = pointer.next;
}
pointer.next = newTask;
}
size++;
}
public String print() {
String result = "";
if (first == null) {
result = "Empty list!\n";
} else {
ToDoListEntry pointer = first;
while (pointer != null) {
result += "Until " + pointer.date + " Task: " + pointer.task +"\n";
pointer = pointer.next;
}
}
System.out.println(result);
return result;
}
}
Related
I have a problem with my nbSandwichs(int type) method
It is supposed to go through the doubly linked list and count how many times a sandwitch of the same type appear, everything is good except for the last sandwich that prints 0 which is something that I don't understand, my check method is saying that it doesn't exist but when I created a get last method, it actually does exist. What condition is missing in my nbSandwichs method ? Does my while loop actually doesn't get to the last node??
Thank you
main class :
Sandwich s1 = new Sandwich(1);
Sandwich s1 = new Sandwich(1);
Sandwich s2 = new Sandwich(15);
Sandwich s3 = new Sandwich(15);
Sandwich s4 = new Sandwich(4);
Sandwich s5 = new Sandwich(15);
APreparer a1 = new APreparer();
a1.addfirst(s1);
a1.addfirst(s2);
a1.addfirst(s3);
a1.addfirst(s4);
a1.addfirst(s5);
System.out.println(a1.nbSandwichs(15)); // PRINTS : 3 OK
System.out.println(a1.nbSandwichs(1)); // PRINTS : 0 NOT OK
public class Sandwich {
private int type;
public Sandwich(int type) {
this.type = type;
commandes[type]++;
}
public class APreparer {
private UneCommande first;
private UneCommande last;
public void addfirst(Sandwich sandwich) {
UneCommande nouvelle = new UneCommande(sandwich);
if (first == null) {
first = nouvelle;
last = nouvelle;
} else {
first = first.addFirst(sandwich);
}
}
int nbSandwichs(int type) {
if (first == null) {
return 0;
} else {
return first.nbSandwichs(type);
}
}
}
public class UneCommande {
private Sandwich sandwich;
private UneCommande next;
private UneCommande previous;
public UneCommande(Sandwich sandwich) {
this.sandwich = sandwich;
}
public UneCommande addFirst(Sandwich sandwich) {
UneCommande current = this;
UneCommande newSand = new UneCommande(sandwich);
newSand.next = current;
this.previous = newSand;
return newSand;
}
int nbSandwichs(int type) {
int counter = 0;
UneCommande current = this;
if (!(check(type))) {
return 0;
} else {
while (current.next != null) {
if (current.sandwich.getType() == type) {
counter++;
}
current = current.next;
}
}
return counter;
}
boolean check(int type) {
UneCommande current = this;
while (current != null) {
if (current.sandwich.getType() == type) {
System.out.println("EXIST");
return true;
}
current = current.next;
}
return false;
}
}
Your loop counts nodes as long as current.next != null. When current is the last node in your list, current.next will be null, and thus not counted.
I was trying to do the deep copy of my linked list known as DictionaryNode which I did but i was not able to display it's content in display method as it is always null. why DictinaryNode temp is always null ? and if i try to assign temp = head work but with temp = copy doesn't.
public class ListOfNodes {
public class DictionaryNode {
protected String word;
private int level;
private DictionaryNode next;
private int space = 0;
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
System.out.println(temp.word)
temp = temp.next;
}
}
public DictionaryNode( String word, int level ) {
this.word = word;
this.level = level;
next = null;
}
}
private DictionaryNode head = null;
public DictionaryNode copy = null;
//used to do deep copy
public void Clone() {
DictionaryNode temp = head.next;
while( temp != null ) {
copy = new DictionaryNode( temp.word , temp.level );
copy = copy.next;
temp = temp.next;
}
}
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
Sytem.out.println(temp.word)
temp = temp.next;
}
}
This program will demonstrate how to do a deep copy on a list. It's more generic than your specific example so hopefully it helps others too.
public class Java_Practice {
private static class LinkedListTest {
private String data;
private LinkedListTest next;
public LinkedListTest(String data) {
super();
this.data = data;
}
public String getData() {
return data;
}
public LinkedListTest getNext() {
return next;
}
public void setNext(LinkedListTest next) {
this.next = next;
}
#Override
public String toString() {
return "LinkedListTest [data=" + data + ", next=" + next + "]";
}
}
// Do a deep copy
private static LinkedListTest copyLlt(LinkedListTest original) {
LinkedListTest copy = new LinkedListTest(original.getData() + " copied");
LinkedListTest nextCopy = original.getNext();
LinkedListTest current = copy;
while (nextCopy != null) {
LinkedListTest newCopy = new LinkedListTest(nextCopy.getData() + " copied");
newCopy.setNext(nextCopy.getNext());
current.setNext(newCopy);
current = newCopy;
nextCopy = newCopy.getNext();
}
return copy;
}
public static void main(String[] args) {
LinkedListTest firstLlt = new LinkedListTest("First");
LinkedListTest secondLlt = new LinkedListTest("Second");
LinkedListTest thirdLlt = new LinkedListTest("Thrid");
firstLlt.setNext(secondLlt);
secondLlt.setNext(thirdLlt);
LinkedListTest copiedLlt = copyLlt(firstLlt);
// Data should say First, Second, Third
System.out.println("Original LinkedListTest: " + firstLlt.toString());
// Data should say First Copied, Second Copied, Third Copied
System.out.println("Copied LinkedListTest: " + copiedLlt.toString());
}
}
In your Clone method you never assign a next field for the copied content. You need to do this to have more than a single connected node in the copy. Furthermore you need to copy the head too. Moreover do must not overwrite copy with anything but the copy of the head:
copy = new DictionaryNode(null, head.level);
DictionaryNode temp = head.next;
DictionaryNode current = copy;
while( temp != null) {
DictionaryNode nn = new DictionaryNode( temp.word , temp.level);
current.next = nn;
current = nn;
temp = temp.next;
}
I have a bunch of dates added to a todo list list2016 and now I need these todo list items to be ordered by date (soonest first, latest last).
It should all happen inside my add method but I have no clue how to do so. Any ideas?
public class ToDoListEntry
{
String task;
LocalDate date;
ToDoListEntry next;
public ToDoListEntry(LocalDate date, String task)
{
this.task = task;
this.date = date;
}
}
Then comes the next where I tried to add an array but which did not work:
public class ToDoList
{
ToDoListEntry first;
int size;
public ToDoList ()
{
first = null;
size = 0;
}
public void add(ToDoListEntry newTask)
{
if (first == null)
{
first = newTask;
}
else
{
ToDoListEntry zeiger = first;
while (zeiger.next != null)
{
zeiger = zeiger.next;
}
zeiger.next = newTask;
}
size++;
}
public String print()
{
String result = "";
if (first == null)
{
result = "Empty list!\n";
}
else
{
ToDoListEntry pointer = first;
while (pointer != null)
{
result += "Until " + pointer.date + " Task: " + pointer.task + "\n";
pointer = pointer.next;
}
}
System.out.println(result);
return result;
}
}
And in the end, the main class. It is supposed to create a new ToDoList and print it out (Note that I did not include the print() method):
public class MyMainClass
{
public static void main(String[] args)
{
System.out.println("Test 00: Empty List");
ToDoList list2016 = new ToDoList();
list2016.print();
System.out.println("Test 01: add");
list2016.add(new ToDoListEntry(LocalDate.of(2016, 8, 15), "Do workout"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 6, 3), "Buy apples"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 10, 11), "Read Books"));
list2016.print();
}
}
This is an inefficient and messy way of doing it. However to achieve what you want I changed two of your classes. These classes were your ToDoList class and your main class.
ToDoList.java
import java.util.*;
import java.time.*;
public class ToDoList
{
ToDoListEntry first;
ArrayList<LocalDate> datesList = new ArrayList();
ArrayList<String> results = new ArrayList();
public ToDoList ()
{
first = null;
}
public void add(ToDoListEntry newTask)
{
if (first == null)
{
first = newTask;
}
else
{
ToDoListEntry zeiger = first;
while (zeiger.next != null)
{
zeiger = zeiger.next;
}
zeiger.next = newTask;
}
}
public void sortDates()
{
Collections.sort(datesList);
}
public void compareAndSort()
{
ArrayList<String> tempDates = new ArrayList();
for(LocalDate lD:datesList)
{
tempDates.add(lD+"");
}
ArrayList<String> tempSorted = new ArrayList();
for(String s:tempDates)
{
for(String a:results)
{
if(a.contains(s))
{
if(!tempSorted.contains(a))
{
tempSorted.add(a);
}
}
}
}
results=tempSorted;
for(String s:results)
{
System.out.println(s);
}
}
public String print()
{
String result = "";
if (first == null)
{
result = "Empty list!\n";
System.out.println(result);
}
else
{
ToDoListEntry pointer = first;
while (pointer != null)
{
result += "Until " + pointer.date + " Task: "+ pointer.task +"\n";
if(LocalDate.now().isBefore(pointer.date))
{
results.add("Until " + pointer.date + " Task: "+ pointer.task);
}
datesList.add(pointer.date);
pointer = pointer.next;
}
}
return result;
}
public String printDates()
{
String dates = datesList.toString();
System.out.println(dates);
return dates;
}
}
Test.java (This is what you described as your main class)
import java.util.*;
import java.time.*;
import java.util.*;
import java.time.*;
public class Test
{
public static void main(String[] args)
{
System.out.println("Test 00: Empty List");
ToDoList list2016 = new ToDoList();
list2016.print();
System.out.println("Test 01: add");
list2016.add(new ToDoListEntry(LocalDate.of(2016, 8, 15), "Do workout"));
list2016.add(new ToDoListEntry(LocalDate.of(2015, 2, 18), "Hand in Homework"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 6, 3), "Buy apples"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 10, 11), "Read Books"));
list2016.add(new ToDoListEntry(LocalDate.of(2016, 10, 11), "Read Homework"));
list2016.print();
list2016.sortDates();
list2016.compareAndSort();
}
}
I have two notes.
The first is since you specifically said soonest I have added a function which removes dates that have already passed the current dates. You could change this later if you like by changing the if statement if(LocalDate.now().isBefore(pointer.date))
Secondly your ToDoList.print() doesn't actually print anything any-more unless first is null.
I am working with java at the moment and I am trying to find out a way to stop printing to the console (for simplicity) after a certain index of a linkedList is reached. Any help explaining this would be much appreciated.
Below is my Node class used to create the list:
protected Integer data;
protected Node link;
public Node(Integer data, Node link) {
this.data = data;
this.link = link;
}
public Node addNodeAfter(Integer element) {
return link = new Node(element, link);
}
public String toString() {
String msg = "";
try {
if (link == null) {
msg = data + " null in tail";
} else {
msg = data + ", " + link.toString();
}
} catch (StackOverflowError e) {
// System.err.println("shit happened here");
}
return msg;
}
public Integer getData() {
return data;
}
public Node getLink() {
return link;
}
Create a method toString(int i) which takes as argument the number of elements which still have to be printed. If the argument is larger than zero and there is a valid link, then recursively call the toString(i - 1) method with i decreased by one:
Code:
public class Node {
public static void main(String[] args) {
Node linkedList = new Node(1, null);
Node node = linkedList;
for (int i = 2; i < 10; ++i)
node = node.addNodeAfter(i);
System.out.println(linkedList.toString(5));
}
public String toString(int i) {
if (i > 0) {
if (link == null)
return data.toString();
else
return data.toString() + " " + link.toString(i - 1);
} else
return "";
}
protected Integer data;
protected Node link;
public Node(Integer data, Node link) {
this.data = data;
this.link = link;
}
public Node addNodeAfter(Integer element) {
return link = new Node(element, link);
}
public Integer getData() {
return data;
}
public Node getLink() {
return link;
}
}
Output
1 2 3 4 5
You will need to extend the LinkedList class and override the toString() method, and then use your subclass.
Something like this:
public class MyLinkedList<E> extends LinkedList<E> {
#Override
public String toString() {
StringBuffer out = new StringBuffer("[");
for (int i=0; i < 3; i++) {
out.append(get(0).toString());
out.append(" ");
}
return out.toString();
}
}
And test it like this:
public class Main {
public static void main(String[] args) {
LinkedList<String> myList = new MyLinkedList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
System.out.println(myList);
}
}
In another class im using the setRating to change the ratings of these songs, however I'm not sure what I need to do to this code to be able to change the rating permanently. Thanks in advance.
import java.util.*;
public class LibraryData {
static String playCount() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
static int setRating(int stars) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private static class Item {
Item(String n, String a, int r) {
name = n;
artist = a;
rating = r;
}
// instance variables
private String name;
private String artist;
private int rating;
private int playCount;
public String toString() {
return name + " - " + artist;
}
}
// with a Map you use put to insert a key, value pair
// and get(key) to retrieve the value associated with a key
// You don't need to understand how this works!
private static Map<String, Item> library = new TreeMap<String, Item>();
static {
// if you want to have extra library items, put them in here
// use the same style - keys should be 2 digit Strings
library.put("01", new Item("How much is that doggy in the window", "Zee-J", 3));
library.put("02", new Item("Exotic", "Maradonna", 5));
library.put("03", new Item("I'm dreaming of a white Christmas", "Ludwig van Beethoven", 2));
library.put("04", new Item("Pastoral Symphony", "Cayley Minnow", 1));
library.put("05", new Item("Anarchy in the UK", "The Kings Singers", 0));
}
public static String listAll() {
String output = "";
Iterator iterator = library.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
Item item = library.get(key);
output += key + " " + item.name + " - " + item.artist + "\n";
}
return output;
}
public static String getName(String key) {
Item item = library.get(key);
if (item == null) {
return null; // null means no such item
} else {
return item.name;
}
}
public static String getArtist(String key) {
Item item = library.get(key);
if (item == null) {
return null; // null means no such item
} else {
return item.artist;
}
}
public static int getRating(String key) {
Item item = library.get(key);
if (item == null) {
return -1; // negative quantity means no such item
} else {
return item.rating;
}
}
public static void setRating(String key, int rating) {
Item item = library.get(key);
if (item != null) {
item.rating = rating;
}
}
public static int getPlayCount(String key) {
Item item = library.get(key);
if (item == null) {
return -1; // negative quantity means no such item
} else {
return item.playCount;
}
}
public static void incrementPlayCount(String key) {
Item item = library.get(key);
if (item != null) {
item.playCount += 1;
}
}
public static void close() {
// Does nothing for this static version.
// Write a statement to close the database when you are using one
}
}
Inside Item, you should write this method:
public static void setRating(int rating0) {
rating = rating0;
}
You should also change your instance variables into static variables by calling them "public static" instead of just "public."