Here I have the code that contains only one method that has 2 parameters. First one is of type linkedlist and second one is of type String. The idea here is that I call this function from the main method several time and each new item that gets added should be sorted from A-Z. But for some reason if I don't add return in the function (
else if(compareResult>0) {
iterator.previous();
iterator.add(element);
return;
}
)
then I get empty list printed out. Why is that?
public class Main {
public static void main(String[] args) {
LinkedList<String> list=new LinkedList<>();
addAndSortElements(list,"a");
addAndSortElements(list,"b");
addAndSortElements(list,"c");
addAndSortElements(list,"f");
addAndSortElements(list,"d");
System.out.println(list);
}
private static void addAndSortElements(LinkedList<String> linkedList, String element) {
var iterator= linkedList.listIterator();
while (iterator.hasNext()) {
String editedElement=element.toLowerCase();
int compareResult=iterator.next().toLowerCase().compareTo(editedElement);
if(compareResult==0) {
System.out.println("Element is already on the list");
***return;***
}
else if(compareResult>0) {
iterator.previous();
iterator.add(element);
return;
}
else {
}
}
iterator.add(element);
}
}
```
`
I have tried everything I said above.
Related
I have the following execution which contains three methods. plus adds a string to the class, minus removes it, and empty checks and returns true if there are no more strings stored.
private static void test() {
Stack<String> stack = new Stack<String>();
stack.plus("hello1");
stack.plus("hello2");
stack.plus("hello3");
stack.plus("hello4");
while (!stack.empty()) {
System.out.println(stack.minus());
}
stack.plus("a1");
stack.plus("a2");
stack.plus("a3");
stack.plus("a4");
stack.minus();
stack.minus();
stack.plus("a5");
stack.plus("a6");
while (!stack.empty()) {
System.out.println(stack.minus());
}
}
#SuppressWarnings("hiding")
public class Stack<String> {
private String e;
public void plus(String e) {
this.e= e;
}
public String minus() {
return e;
}
public boolean empty() {
if(e != null) {
}return false;
}
}
The output should be:
hello4
hello3
hello2
hello1
a6
a5
a2
a1
My program at the moment keeps looping infinitely at "hello4" and I can't quite figure out how to fix my empty function. I suspect that method is my main issue.
You seem to misunderstand the syntax of generics. In your Stack class, the generic parameter String behaves a lot more like a variable, not like the String class.
//DataType is substituted for whatever you tell it in <...> when making a Stack object
public class Stack<DataType> {
private List<DataType> memory = new ArrayList<>();
public void push(DataType e) {
memory.add(e);
}
public DataType pop() {
if(memory.isEmpty())
return null;
int lastIndex = memory.size()-1;
DataType element = memory.get(lastIndex); //get last element of memory
memory.remove(lastIndex); //remove it from the stack
return element; //return it
}
public boolean isEmpty() {
return memory.isEmpty();
}
}
which you can then use like you already are:
Stack<String> stack = new Stack<String>(); //DataType in Stack becomes String
import java.util.ArrayList;
public class list {
protected ArrayList<String> a = new ArrayList<String>();
public boolean ad(String aa)
{
boolean t=true;
a.add(aa);
for(String value : courses)
{
if(a.contains(value))
{
a=false;
}
else
{
a=true;
}
}
return a;
}
}
this program should return false if arraylist course contains duplicate elements.else if we are inserting new element return true.
expected output for above code is
true
but it only returns false for any condition.
You can simply utilize ArrayList#contains to verify if an element already exists within the List.
public boolean addCourse(String course) {
if (courses.contains(course)) {
return false;
}
return courses.add(course);
}
You are adding course in the list and then iterating thr the list, so it always gives you true. ArrayList allows duplicates.
if(courses.contains(value))
will always return true as you are adding the course before this in arraylist.
Suggestion: You should use Set than list if you want to avoid duplicates.
Instead of using ArrayList, how about using HashSet to keep your courses ?
http://beginnersbook.com/2013/12/hashset-class-in-java-with-example/
Try the code below:
import java.util.ArrayList;
public class list {
protected ArrayList<String> courses = new ArrayList<String>();
protected String temp = "";
public list(String str, String str2) {
}
public boolean addCourse(String course) {
boolean a = true;
if (courses.isEmpty()) {
courses.add(course);
temp = course;
} else {
if (temp.equalsIgnoreCase(course)) {
a = false;
temp = "";
} else {
a = true;
courses.add(course);
temp = course;
}
}
return a;
}
public static void main(String[] args) {
list inst = new list("John", "WIU");
System.out.println(inst.addCourse("CS560"));
System.out.println(inst.addCourse("CS500"));
}
}
Simple way you can do:
For Each time executing else block so. remove else block it will work.
for(String value : courses)
{
if(courses.contains(value))
{
a=false;
break;
}
a=true;
}
Im working on a LinkedListStack and have to print out for example "size".
here is my LinkedListStack:
public class LinkedListStack {
private class Element {
public Object value;
public Element next;
}
private Element top;
private int size=0;
public void push(Object o) {
Element e=new Element();
e.value=o;
e.next=top;
top=e;
size++;
}
public Object pop() {
if (top!=null) {
Object v=top.value;
top=top.next;
size--;
return v;
} else {
return null;
}
}
public boolean isEmpty(){
return top==null;
}
public int size() {
return size;
}
public Object get(int n) {
Element current=top;
int i=0;
while (i<n && current!=null) {
current=current.next;
i++;
}
if (current==null)
return null;
else
return current.value;
}
}
I know I have to use
System.out.println ("...");
and that i need a new class, let's call it Stacki. Is must contain a main method where i can use the methods and print them out. So that would be:
public class Stacki {
public static void main(String[] args) {
}
}
how do I put
public void size() {
System.out.println ("size is"+size());
}
in that class? Because i cannot use the block as such, an error occurs.
Thank you :)
You instantiate your other class within Stacki, like:
public class Stacki {
public static void main(String[]) {
LinkedListStack stack = new LinkedListStack();
System.out.println("size is: " + stack.size());
... then you probably add some elements, remove some, and whenever you want to:
System.out.println("size is: " + stack.size());
And hint: Stacki is a rather nothing-saying name. Better call that class LinkedListStackTester or something alike. Names always say what the thing they denote is about!
And finally: this is really basic stuff. It doesn't make much sense to create your own stack class, when you have no idea how to put that to use. In that sense: you probably want to spend some hours here and work yourself through those tutorials!
So I have an arraylist which stores different objects about the universe (planet, comet, star etc). Instead of doing this:
planet.decreaseLifeTime(1);
star.decreaseLifeTime(1);
comet.decreaseLifeTime(1);
Every iteration of the game I want it to reduce the life time by 1. I tried this but it doesn't work:
private ArrayList<SpaceObject> universeEntities;
public void reduceLifeTime() {
for (SpaceObject entity: universeEntities) {
entity.decreaseLifeTime(1);
if(entity.getLifeTime() <= 0) {
erase(entity);
System.out.println("This entity has been erased");
}
System.out.println("life time: " + entity.getLifeTime());
}
}
Objects are added like so:
planet = new Planet(500, 500, -2, -2, 25, Color.BLUE, this);
universeEntities.add(planet);
If erase(entity) is modifying the universeEntities list java will get mad.
You can either store the SpaceObject you want to erase in a separate list and then erase them after the for loop.
or
You can loop over the universeEntities without using an iterator
e.g. a numerical index
According to your implementation of the reduceLifeTime method, the problem may be in calling erase method in it (depends how it is implemented).
If erase method just tries to remove an item from universeEntities collection by calling ArrayList's remove method it just break an iterator.
Consider reimplementing your method to:
public void reduceLifeTime() {
Iterator<SpaceObject> iterator = universeEntities.iterator();
while (iterator.hasNext()) {
SpaceObject object = iterator.next();
object.decreaseLifeTime(1);
if(object.getLifeTime() <= 0) {
iterator.remove();
System.out.println("This entity has been erased.");
}
System.out.println(String.format("Life time: %d", object.getLifeTime()));
}
}
Fully working sample:
public class Test {
private ArrayList<SpaceObject> universeEntities = new ArrayList<SpaceObject>();
public Test() {
universeEntities.add(new Planet());
universeEntities.add(new Planet());
}
public void reduceLifeTime() {
Iterator<SpaceObject> iterator = universeEntities.iterator();
while (iterator.hasNext()) {
SpaceObject object = iterator.next();
object.decreaseLifeTime(1);
if(object.getLifeTime() <= 0) {
iterator.remove();
System.out.println("This entity has been erased.");
}
System.out.println(String.format("Life time: %d", object.getLifeTime()));
}
}
public static void main(String[] args) {
Test test = new Test();
while(true) {
test.reduceLifeTime();
// Endless loop. Need a quit condition.
}
}
public static class SpaceObject {
protected int life = 0;
public SpaceObject(int life) {
this.life = life;
}
public void decreaseLifeTime(int value) {
this.life -= value;
}
public int getLifeTime() {
return life;
}
}
public static class Planet extends SpaceObject {
public Planet() {
super(10);
}
}
}
If you do not want to use iterators you can collect items that should be removed in some kind of collection, return from reduceLifeTime method and remove using removeAll afterwards.
I'm trying to make a copy lists method as this one Collections.copy(,);
I want to make it my self so I made this one
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NewMain {
public static void main(String[] args) {
String[] a1={"asdasd","sadasd","asdasd"};
List<String> l1= Arrays.asList(a1);
String[] a2=new String[3];
List<String> l2= Arrays.asList(a2);
copy(l1,l2);
}
public static void copy(List<String> copy_from,List<String> copy_to){
for(int i=0;i<=copy_from.size();i++){
System.out.print( copy_from.containsAll(copy_to));
}
}
}
I know the problem from containsAll method , but what should I use ?
for(int i=0;i<=copy_from.size();i++){
System.out.print( copy_from.containsAll(copy_to));
}
Does nothing besides a sysout statement.
You want something along the lines of:
public static void copy(List<String> copy_from,List<String> copy_to){
if (copy_from.size() > copy_to.size())
throw new IndexOutOfBoundsException("Source does not fit in dest");
} else {
for(String toCopy : copy_from) {
copy_to.add(toCopy);
}
}
}
This is a for each loop that loops over every element in your copy_from list and adds it to your copy_to list.
This will behave the same way as Collections.copy.
public static void copy(List<String> copy_from,List<String> copy_to){
if (copy_to.size() < copy_from.size()) {
throw new IndexOutOfBoundsException("copy_to is too small.");
}
ListIterator<String> fromIter = copy_from.listIterator();
ListIterator<String> toIter = copy_to.listIterator();
while (fromIter.hasNext()) {
String next = fromIter.next();
toIter.next();
toIter.set(next);
}
}
I assume that you don't want to copy elements that are already there.
Then you can do it this way:
public static void copy(List<String> copy_from,List<String> copy_to){
if(copy_to==null){throw Exception("copy_to can't be null!")}
//additional checks should be added
for(String elem : copy_from){
if(!copy_to.contains(elem)){
copy_to.add(elem);
}
}
}
This should do assuming copy_from and copy_to can grow as we add elements.
public static void copy(List<String> copy_from,List<String> copy_to) throws Exception {
//handle exception according to your wish
if (copy_from !=null && copy_to == null) {
throw new Exception("Source is not empty by Destination is null");
}
for(String string : copy_from){
copy_to.add(string);
}
}