This is my assignment, and I am not sure how to proceed. The output only prints my first four teachers, and I don't know why it isn't printing my last three teachers as well. Thanks!
Create an ArrayList called teachers. Fill the ArrayList with your teacher’s LAST NAMES ONLY in the order that you see them during the day (Period 1: Jensen, Period 2: Houge, Period 3: …, etc.) You only need to put the teacher’s last name in the ArrayList, so it would print [Jensen, Houge, etc…].) Print the ArrayList using a print method.
Write a method that takes your teachers ArrayList, and from it makes a new ArrayList called ordered, whererin your teacher’s names are now in lexicographic order. Print the resulting ArrayList. (DO NOT CHANGE YOUR ORIGINAL ARRAYLIST, MAKE A NEW ONE!)
import java.util.ArrayList;
public class LexicographicOrdering
{
public static void main (String [] args){
ArrayList<String> teachers = new ArrayList<String>();
teachers.add("Turnbow");
teachers.add("Dyvig");
teachers.add("Williams");
teachers.add("Houge");
teachers.add("Allaire");
teachers.add("Violette");
teachers.add("Dorgan");
System.out.println(teachers);
order(teachers);
}
public static void order(ArrayList<String> teachers ){
ArrayList<String> ordered = new ArrayList<String>();
for(int i = 0; i < teachers.size(); i++){
String str = teachers.get(i);
for(int j = 1; j < teachers.size(); j++){
if(str.compareTo(teachers.get(j)) > 0){
str = teachers.get(j);
}
}
ordered.add(str);
teachers.remove(str);
}
System.out.print(ordered);
}
}
So the issue here is with your static order method. As Karl suggests above, you want to break the method into two separate parts. The first will create an ArrayList named 'ordered' and then fill it with the data contained in the 'teachers' array.
ArrayList<String> ordered = new ArrayList(); //the second <String> is not required
for(int i = 0; i < teachers.size(); i++){
String str = teachers.get(i);
ordered.add(str);
}
The next objective is to sort the array in alphabetical order, which can be achieved using the Collections.sort(ArrayList) method which is contained in the java.util package.
Collections.sort(ordered);
And now you need to print the ArrayList.
System.out.println(ordered);
As this is a homework assignment, I would recommend reading up on the Collections.sort() method, along with an example of it. A quick google search pulled up the following website: http://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/
Also, I would recommend reading the API for the Collection class. https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-
Edit:
At a quick glance, I would assume the reason that your string is cutting out the last 3 names is due to the fact that you are removing items from the list as you are looking at each position in the list. Essentially, you are looking at every other item in the list because of this.
So I figured it out! I only needed to set the first for loop back to zero. Here is the new code:
import java.util.ArrayList;
public class LexicographicOrdering
{
public static void main (String [] args){
ArrayList<String> teachers = new ArrayList<String>();
teachers.add("Turnbow");
teachers.add("Dyvig");
teachers.add("Williams");
teachers.add("Houge");
teachers.add("Allaire");
teachers.add("Violette");
teachers.add("Dorgan");
System.out.println(teachers);
order(teachers);
}
public static void order(ArrayList<String> teachers ){
ArrayList<String> ordered = new ArrayList<String>();
for(int i = 0; i < teachers.size(); i++){
String str = teachers.get(i);
for(int j = 1; j < teachers.size(); j++){
if(str.compareTo(teachers.get(j)) > 0){
str = teachers.get(j);
}
}
i =- 1;
ordered.add(str);
teachers.remove(str);
}
System.out.print(ordered);
}
}
Related
How to add as many elements as I want to an array list - with only one insert operation?
I want to add 5 Items to a buy list with one input. And then I want to print the 5 items out.
This is what I have done now:
package paket1;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JOptionPane;
public class Class2 {
public static void main(String[] args) {
int i = 0;
while (i != 5) {
String Eingabe = JOptionPane.showInputDialog("Add Einkaufsliste");
ArrayList<String> einkaufsListe = new ArrayList<>();
einkaufsListe.add(Eingabe);
}
}
}
Each time your iteration runs, you are creating a new, empty list, and adding one element to it. But this loop will never finish, because i is never incremented, and will always be 0. The correct code would look like this:
int i = 0;
List<String> einkaufsListe = new ArrayList<>();
while (i <= 5) {
String eingabe = JOptionPane.showInputDialog("Add Einkaufsliste");
einkaufsListe.add(eingabe);
i++;
}
And then you will have to print it as well.
I think it is better to extract this logic into separate method, that retrieves required list. If you want to use ArrayList, do not forget to set initial size.
public static List<String> gibAlleEinkaufe(int insgesamt) {
List<String> einkaufsListe = new ArrayList<>(insgesamt);
for(int i = 0; i < insgesamt; i++)
einkaufsListe.add(JOptionPane.showInputDialog("Add Einkaufsliste"));
return einkaufsListe;
}
I am new to Java & Junit testing. My question is, how to fix the error I am getting with the following Junit test code. The Java code returns the desired output when checked with a print statement. Any help is greatly appreciated.
Junit test code
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
public class RemoveDuplicateTest {
#Test
public void test() {
RemoveDuplicatesStringArray rd = new RemoveDuplicatesStringArray();
String[] strArray = {"ellen","talk","show","ellen","talk","show","ellen","talk"};
rd.removeDups(strArray);
assertEquals(Arrays.asList("show","ellen","talk"),strArray.toString());
}
}
Java code:
import java.util.*;
public class RemoveDuplicatesStringArray {
public List<String> removeDups(String[] str){
List<String> strList = new ArrayList<>();
int count = 0;
for(int i = 0; i < str.length; i++){
for(int j = i+1; j < str.length; j++){
if(str[i].equals(str[j])){
count += 1;
}
}
if(count < 1){
strList.add(str[i]);
}
count = 0;
}
for(int k = 0; k < strList.size(); ){
System.out.println("check "+strList);
System.out.println(strList.getClass());
return(strList);
}
return null;
}
}
To answer you question, your test has a couple of errors:
String[] strArray = {"ellen","talk","show","ellen","talk","show","ellen","talk"};
rd.removeDups(strArray);
removeDups leaves the passed array unchanged and you ignore the result that should be the list containing only the unique elements.
assertEquals(Arrays.asList("show","ellen","talk"),strArray.toString());
Here you compare a list with the string representation of a String array. This will never be evaluated as equal. Even if you change it to
assertEquals(Arrays.asList("show","ellen","talk").tostring(), Arrays.asList(strArray).toString());
you still compare the complete array with all duplicate values with the one with unique values leading to the same result.
I suppose you wanted to do the foll
public void test() {
RemoveDuplicatesStringArray rd = new RemoveDuplicatesStringArray();
String[] strArray = {"ellen","talk","show","ellen","talk","show","ellen","talk"};
List<String> checkList = rd.removeDups(strArray);
assertEquals(Arrays.asList("ellen","talk","show").tostring(),checkList.toString());
}
I changed the order of the values in the list containing the expected values because the values are added to the resulting list in the order they appear in the source list the first time. Otherwise your check will still be negative.
BTW: removeDups is a performance hell. As mentioned in the comments, using HashSet or similar classes are much better because they are
Already available, so you don't need to reinvent the wheel
Much faster because they don't iterate over the whole target list for each input-element
I am making a program which has to sort every English word based on the first two letters. Each group of two letters has it's own list which I have to add the words into therefore I have 676 lists in total. I tried making an ArrayList of Lists to do this:
public static List<List<String>> englishWordList = new ArrayList<List<String>>(673);
Now when I try to add elements to one of the lists I get this an IndexOutOfBoundsException
private static void letterSort(String s){
//Sorts the words by the first two letters and places in the appropriate list.
String letterGet = s.substring(0,2);
for(int i = 0; i < 676; i++){
if(letterGet.equals(letterCombos[i])){
Debug(s);
Debug(letterGet);
try{
englishWordList.get(i).add(s); \\IndexOutOfBoundsException here
}catch(Exception e){
e.printStackTrace();
System.exit(0);
}
}
}
Any help with fixing this would be very appreciated, also if any more information is needed I will be more than happy to add it.
You only initialized the englishWordList, but you didn't add anything to it. Therefore englishWordList is empty and any get(int) call will throw an IndexOutOfBoundsException.
You can fill it with empty Lists the following way (also note that you set initial capacity to 673 instead of 676):
public static List<List<String>> englishWordList = new ArrayList<List<String>>(676);
static {
for (int i = 0; i < 676; i++) {
englishWordList.add(new ArrayList<String>());
}
}
Ok, I'm new to this site but I do know that I'm not supposed to ask HW questions on here, but what I am asking is indeed HW BUT it has already been finished and submitted (and graded), I'm just here to hopefully get my program running with a better understanding:)
To prove that I've already completed it and not trying to pull a fast one, here's a link to the submission page:
http://i959.photobucket.com/albums/ae76/GoWxGaiA/HWDone_zps8ae79bf7.png
Now on the program...I'm supposed to be creating a program that checks for duplicate strings from the user input, and then output all the 'unique' strings in sorted order (ones that were not duplicates), and then output the 'non-unique' ones in sorted order right underneath the prior output. My instructor told us that we had to use a 'Triple nested loop' which I assume is just a for loop inside a for loop inside a for loop...I get all the up to the point where I need to store the strings in an array in which case I cannot and have not found another way around. What I submitted for this assignment is this:
package Homework2;
import java.util.Scanner;
public class Homework2 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a list of words:");
String[] words = stdin.nextLine().split(" ");
System.out.println(words.length);
String[] array = new String[words.length];
for (int i = 0; i < words.length; i++) {
if(words == words)
for (int j = 0; j < words.length; j++) {
array[j] = words;
System.out.println(array[j]);
}
}
}
}
Again, I want to stress that I've already submitted this assignment and am just looking to properly complete this assignment to further my understanding.
Any help would be greatly appreciated!
A rather simple solution that I like to use for this problem:
Set<String> used = new HashSet<>();
public boolean wasUsed(String s) {
return used.add(s);
}
//using the method
if (wasUsed(yourString)) {
// duplicate!
}
Sets contain only 1 of an element, and will return false when adding a duplicate. Makes things really easy for management.
As for your scenario, I would simply keep a separate Set of words, and remove them when you hit a duplicate.
You can read up more on Java's Collections To learn about these helpful tools.
There are two obvious compile-time problems with this code:
words == words is always true. I guess you are trying to test wether there is a duplicate with this line, but this is not the way to do this.
array[j] = words tries to assign a String[] to a String variable.
This assignment is actually a little bit harder than it would seem at first glance. The trickiest part is printing the unique string in sorted order. The most practical solution is to use a linked list for this, which allows easy insertion in the middle of the list. I did assume that the use of Collections.sort() was not allowed. I guess it's possible that the use of LinkedList is also not allowed, but you didn't mention that in your question.
String[] words = { "1", "4", "2", "4", "3", "1" };
LinkedList<String> unique = new LinkedList<String>();
LinkedList<String> duplicates = new LinkedList<String>();
unique.add(words[0]);
for (int i = 1; i < words.length; i++)
{
boolean found = false;
for (String uniqueWord : unique)
{
if (words[i].equals(uniqueWord))
{
duplicates.add(words[i]);
found = true;
break;
}
}
if (!found)
{
boolean added = false;
for (int index = 0; index < unique.size(); index++)
{
if (words[i].compareTo(unique.get(index)) < 0)
{
unique.add(index, words[i]);
added = true;
break;
}
}
if (!added)
unique.addLast(words[i]);
}
}
for (String word : unique)
System.out.println(word);
System.out.println("--");
for (String word : duplicates)
System.out.println(word);
This is what I have
ArrayList <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
Collections.sort(cdList, String.CASE_INSENSITIVE_ORDER);
System.out.println(cdList);
bigBox.setText("Original Order\n**************\n");
for (int i = 0; i < cdList.size(); i++) {
bigBox.setText(bigBox.getText()+""+cdList.get(i)+"\n");
}
bigBox.setText(bigBox.getText()+"\n\nSorted Order\n************\n");
Collections.sort(cdList);
for (int j = 0; j < cdList.size(); j++) {
bigBox.setText(bigBox.getText()+""+);
}
I want the 4 examples outputted in their original order, and in alphabetical order. What am I doing wrong?
You are adding only one element (String) to the list, a concatenated string.
Change this
ArrayList <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
to
List <String> cdList = new ArrayList<String>();
Collections.addAll(cdList, "ExampleA","ExampleB","ExampleC","ExampleD");
Read more Collections#addAll
And for showing you should use append rather than setText.
Example:
bigBox.append("Original Order\n**************\n");
for (String s : cdList) {
bigBox.append(s);
bigBox.append("\n");
}
I assume your elements are meant to be the strings "ExampleA", "ExampleB", "ExampleC", and "ExampleD". If the is the case, what you are currently doing in your call to Collections.addAll() is adding them to cdList as one long string. the + operator, when used on strings, appends them. What you probably want it to separate them with commas, so that instead of having:
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
you have:
Collections.addAll(cdList, "ExampleA\n", "ExampleB\n", "ExampleC\n", "ExampleD");