I a homework where I need to merge two linkedlist, "songs" list and "artists" linked list, it works on the first list the "song" list, but whenever i add another list it just wont work
as you can see here the public static void now has errors
package mergedlinkedlist;
import java.util.LinkedList;
public class Mergedlinkedlist {
public static void main(String[] args) {
LinkedList<String>song = new LinkedList<>();
song.add("imagine");
song.add("bohemian rhapsody");
song.add("highway to hell");
System.out.println(song);
}
public static void main(String[] args) {
LinkedList<String>artists = new LinkedList<>();
artists.add("john lennon");
artists.add("queen");
artists.add("ACDC");
System.out.println(artists);
}
Okey, as one comment has pointed out, no program can have 2 main methods. You cannot create another one.
I suggest to integrate the code from your second into your first. You can safely just add the contents together.
The task is to merge the lists. Do you need any more help with that?
Assuming the task says you know the size of the list you can just create a new list and use the same method you used above to add them to the list. If you do not, you will need to use a loop. It would look like this:
LinkedList<String>artistsAndSongs = new LinkedList<>();
if (artists.size() == songs.size()) {
for (int i = 0; i < artists.size(); i++) {
artistsAndSongs.add(artists.get(i));
artistsAndSongs.add(songs.get(i));
}
} else {
System.out.println("Not every artist is matched with a song!");
}
But you should read up on how linked lists work exactly in the documentation. This will not only improve your understanding of the class but also teach you how to quickly find solutions to your problem.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
Related
So I have recently started my work on Selenium Webdriver using Java. Below is the code:
List<LineDashboardDetails> LineDashboardDetailList = new ArrayList<LineDashboardDetails>();
LineDashboardDetails objLineDetail = new LineDashboardDetails();
for (int i = 0; i < lineUITextList.size(); i++) {
objLineDetail.lineName=lineUITextList.get(i);
objLineDetail.machineNames = machineUITextList.get(i).toString();
LineDashboardDetailList.add(objLineDetail);
}
System.out.println(LineDashboardDetailList);
I have created a lineUITextList ArrayList of String. This array will always have only 1 value in it. So the issue is above for loop does not work. The loop only executes once and comes out to print the LineDashboardDetailList. The machineUITextList array has around 5-6 values in it. My expectation is to have LineDashboardDetailList such that the lineUITextList common value is paired with each new value of machineUITextList.
For example if lineUITextList= {"Noun"}
machineUITextList= {"Pen","Box","Note","Scale"}
So my list i.e LineDashboardDetailList should give me output as:
Noun,Pen
Noun,Box
Noun,Note
Noun,Scale
I am using LineDashboardDetailList List further in my code.
Thanks in Advance.
I am not totally sure what you are trying to achive. Personally, I would use a java.util.Map to associate each value of the lineUITextList with the list of values of machineUITextList.
However, to help you in achiving your goal, first of all, I would design the LineDashboardDetails class in order to maintain the single value of the lineUITextList, along with the list of machineUITextList, so as you can combine them by using a specific method. That has lots of advantages in terms of encapsulation, distribution of responsabilities, etc.., plus you can always reuse for other purposes.
The function to combine the values can be easily implemented by taking advantages of Java stream and built-in functional interfaces.
Here is the code of the LineDashboardDetails class:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class LineDashboardDetails {
private String lineName;
private List<String> machineNames;
public String getLineName() {
return lineName;
}
public void setLineName(String lineName) {
this.lineName = lineName;
}
public List<String> getMachineNames() {
return new ArrayList<>(machineNames);
}
public void setMachineNames(List<String> machineNames) {
this.machineNames = new ArrayList<>(machineNames);
}
public List<String> getCombinedList() {
return machineNames.stream()
.map(s -> lineName + "," + s)
.collect(Collectors.toList());
}
}
Here is instead the code that you tried to implement, which uses the class above and combine the two list, and finally prints out the list of values as you expect. You can see, I prepared two simple list in the main method, but you can actually generalize it in relation to your own needs:
import java.util.List;
import java.util.ArrayList;
public class SeleniumWebdriverListTest {
public List<LineDashboardDetails> combineUITextListWithMachineUIText(List<String> lineUITextList,
List<String> machineUITextList) {
List<LineDashboardDetails> lineDashboardDetailList = new ArrayList<>();
for (String lineUIText : lineUITextList) {
LineDashboardDetails objLineDetail = new LineDashboardDetails();
objLineDetail.setLineName(lineUIText);
objLineDetail.setMachineNames(machineUITextList);
lineDashboardDetailList.add(objLineDetail);
}
return lineDashboardDetailList;
}
public static void main(String[] args) {
List<String> lineUITextList = new ArrayList<>();
lineUITextList.add("Noun");
List<String> machineUITextList = new ArrayList<>();
machineUITextList.add("Pen");
machineUITextList.add("Box");
machineUITextList.add("Note");
machineUITextList.add("Scale");
List<LineDashboardDetails> lineDashboardDetailList =
new SeleniumWebdriverListTest().combineUITextListWithMachineUIText(
lineUITextList, machineUITextList);
lineDashboardDetailList.stream()
.map(s -> s.getCombinedList())
.forEach(System.out::println);
}
}
I could have used Java streams and a specific lamba expression to implement the combineUITextListWithMachineUIText method as well, but I kept somehow your original version to let you understand my idea of implementation around your code.
Here is the output I get:
[Noun,Pen, Noun,Box, Noun,Note, Noun,Scale]
Feel free to ask for any clarification.
I'm doing a program that gets as parameter more sentences. And I made 2 lists, one called "propozitie", which contains each sentence, and one called "propozitii", which contains all sentences.
The problem is: When I clear the "propozitie" list after it meets a ".", it also clears the "propozitii" list and it's ending up by printing 3 empty lists.
Input data:
Andrei goes there. Andrei plays football. I enjoy staying home.
Can anybody help me ?
Thanks in advance.
import java.util.ArrayList;
import java.util.List;
public class Propozitie {
private static List<List<String>> propozitii;
private static List<String> propozitie;
public static void main(String args[]) {
propozitii = new ArrayList<List<String>>();
propozitie = new ArrayList<String>();
for (String arg : args) {
propozitie.add(arg);
if (arg.contains(".")) {
propozitii.add(propozitie);
propozitie.clear();
}
}
System.out.println(propozitii);
}
}
This is because, the statement
propozitii.add(propozitie);
adds the reference to propozitie to propozitii list. A copy of the object is not added. To do a copy, use this.
propozitii.add(new ArrayList<String>(propozitie));
now you can clear propozitie
I'm currently learning linked list and I have discovered the basics of coding it and I fully understand them. However, I have a certain amount of nodes preset, so the user would not be able to add more. How would one implement a while loop to keep cycling through and asking the user if they want to add another piece of data.
Here is the code that I already have so far:
public class List {
public int x;
public List ptr = null;
}
Above is the object class for List. List contains a data type of x and a pointer.
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
List front = new List();
front.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
List l1 = new List();
l1.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
List l2 = new List();
l2.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
front.ptr = l1;
l1.ptr = l2;
printNodes(front);
}
public static void printNodes(List p) {
while (p != null) {
System.out.print(p.x + " ");
p = p.ptr;
}
}
}
As you can see, I have 3 Nodes created, but you cannot add anymore. I'd like to have something along the lines of:
boolean goAgain = true;
while (goAgain) {
//create a new node
String again = JOptionPane.showInputDialog("Add another node?");
if (!again.equalsIgnoreCase("yes")) {
goAgain = false;
}
}
Thank you!
P.S - I am a sophomore in high school, please use vocabulary that I will be able to understand. I wouldn't say I'm a java noob, but I'm no expert either.
Well I'd clean up your while loop to include everything in one statement. But that's just because I'm lazy. ;)
while (!JOptionPane.showInputDialog("Add another node?").equalsIgnoreCase("yes"))
{
//make a new node
}
As for the code to make a new node I would suggest implementing your List class from the List interface that Java has. You can read about it here. If you're just starting out in Java though it might be a little hard to understand. As a comment on your existing code here:
List front = new List();
front.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
You're not exactly making a new node per-say, you're just creating new instances of your List class. In this case the object is labeled 'front' My suggestion is to read up more on how a List is meant to function. Here is a good example.
I am in the process planning my next homework assignment, which is an anagram finder. I'm using java and would like to know if you can have a Set of Set's, where each Set have the same name currentSet (the names of each set are not unique or dynamically created? If this is too vague I can post my code to put it in context. Regards.
As #Hunter already mentioned, you can have Set of Sets. The code would be something like following:
import java.util.*;
public class TestingSets {
public static void main(String[] args) {
Set<Set<String>> mainSet = new HashSet<Set<String>>();
Set<String> s;
for (int i=0; i<10; i++){
s = new HashSet<String>();
s.add("Hi "+i);
mainSet.add(s);
}
}
}
So I have a null pointer exception when run. I am supposed to create a generic class that implements a list with chunks of arrays added as needed. Each time I add an element it is to check if there is space in the tail chunk array and if so add the element. Else it needs to add a chunk, adjust the pointers and add the element. My problem so far is that when I go to add the first element it is throwing a null pointer exception. I believe I have instantiated and object and assigned it where needed. If anyone has any insight please feel free to let me know what I am doing wrong or maybe its right in front of my face.
"myChunk.chunk_.add(element);////////////error" is where I am getting the error.
package ChunkList;
import java.util.*;
import java.io.*;
public class chunkList<T> {
public static void main(String[] args) {
chunkList<Integer> myList=new chunkList<Integer>();
for(int i=1; i<24; i++)
{
myList.add(i);//////////////////////////////////
System.out.println("Adding number: "+ i);
}
System.out.println("");
myList.display();
}
private chunk head;//changed T to chunk
private chunk tail;//changed T to chunk
private int array_size=8;
private int list_size;
public chunkList()//Default Constructor
{
head=null;
tail=null;
list_size=0;
}
//public chunkList(chunkList copy){}// a copy constructor.... don't think I need.
class chunk// added <T>
{
//T[] chunk_arr = new T[array_size];// illegal operation
//ArrayList<T> chunk_ = new ArrayList<T>(array_size);
ArrayList<T> chunk_;
private int chunk_size; //may need to change to public
chunk nextChunk;//changed T to chunk
chunk prevChunk;//changed T to chunk
public chunk()//default constructor
{
chunk_ = new ArrayList<T>(array_size);
chunk_size=0;
nextChunk=null;
prevChunk=null;
}
}
public void add(T element)
{
if(this.tail==null)//empty chunk list
{
chunk myChunk=new chunk();//instantiate
//myChunk.prevChunk=null;//changed from head to null
//myChunk.nextChunk=null;//changed from tail to null
head=myChunk;
tail=myChunk;
//head.nextChunk=null;
//head.prevChunk=null;
myChunk.chunk_.add(element);////////////error
list_size++;
myChunk.chunk_size=1;
}
else if (this.tail.chunk_size<array_size)//adds the element to the last chunk in list
{
this.tail.chunk_.add(element);//add element
list_size++;
this.tail.chunk_size++;//increase individual chunk array size
}
else// create new chunk, relink chunks, add element
{
chunk myChunk=new chunk();
myChunk.chunk_size=1;
list_size++;
myChunk.chunk_.add(element);
tail.nextChunk=myChunk;
myChunk.prevChunk=tail;
tail=myChunk;
}}
public int size()
{return list_size;}
public void display()
{
chunk my_chunk=head;
if(my_chunk==null)
{
System.out.print("Empty Chunk List");
return;
}
for(int i=0;i<list_size; )
{
for(int j=0; j<my_chunk.chunk_size; j++)
{
System.out.println(my_chunk.chunk_.get(j));
i++;
}
if(my_chunk.nextChunk!=null)
my_chunk=my_chunk.nextChunk;
}
}
}
So thanks Olivier Jacot-Descombes , I fixed one problem with the code and it now adds the first chunk BUT it is throwing NPE when it tries to create the next chunk. I will look at it and be back if i need more help. Thanks All.
P.S. The add method on this was incorrectly linked together in the last else statement.
Your code is very strange
There is a public static void main(String[] args) inside the class chunkList<T>. This makes no sense.
You declare a chunkList<Integer> instead of chunkList<int>.
You re-declare a chunk<T> head and chunk<T> tail in the constructor. The code should simply be head = null; without chunk<T>.
In the constructor of chunk you do the same thing again with ArrayList<T> chunk_ = ....
I could tell more things; however, I think that you should start by fixing these things to begin with.
NAMING STANDARDS PLEASE!
You will immediately benefit from adhering to industry naming standards, because your code will be more easily read by others when you ask for their help. Also, you'll be able to read other's code more easily too.
In java, convention is that:
all names are camelCase
all names start with a lowercase letter, except class names start with a capital letter
constants are all-capitals with underscore separation (eg MY_CONSTANT)
tend not to abbreviate names
don't use hungarian notation
To apply this to your code, make the following changes:
Rename chunkList to ChunkList
Rename array_size to arraySize
Rename my_chunk to myChunk
Rename chunk_ tochunk`
Now, to answer your question, just use a java.util.LinkedList and stop trying to reinvent the wheel!