Compare an Arraylist and give output - java

I have two ArrayLists. How can I compare the elements in the arraylists and create a new list with the results?
I need to iterate through the list to actually get its results and compare. How can I do it in Java?
Any help is appreciated.
Thanks

You can compare by implementing Comparator class.You can understand by below example in which Two Time class is getting compared.
class Time
{
int hours,minutes,seconds;
public Time(int hours,int minutes,int seconds)
{
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
public int getHours()
{
return this.hours;
}
public int getMinutes()
{
return this.minutes;
}
public int getSeconds()
{
return this.seconds;
}
public String toString()
{
return String.format("%d:%02d:%02d %s",((hours==0||hours==12)? 12:hours%12),this.minutes,this.seconds,((hours>=12)?"PM":"AM"));
}
}
class TimeComparator implements Comparator<Time>
{
public int compare(Time t1,Time t2)
{
int hours=t1.getHours()-t2.getHours();
int minutes=t1.getMinutes()-t2.getMinutes();
int seconds=t1.getSeconds()-t2.getSeconds();
if(hours>0)
return 1;
else if(hours<0)
return -1;
if(minutes>0)
return 1;
else if(minutes<0)
return -1;
if(seconds>0)
return 1;
else if(seconds<0)
return -1;
return 0;
}
public boolean equals(Object obj)
{
return true;
}
}
After this you can use Collections class to use any method like sorting or search.

I hope that the following chunck of code will get you started.
import java.util.ArrayList;
class Compare {
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("Hello");
a.add("Goodbye");
ArrayList<String> b = new ArrayList<String>();
b.add("Hello");
b.add("Bye");
if (a.size() != b.size()) {
System.out.println("Arrays must have the same size");
return;
}
ArrayList<Boolean> results = new ArrayList<Boolean>();
for(int i = 0; i < a.size(); ++i)
results.add(a.get(i).equals(b.get(i)));
for(int i = 0; i < a.size(); ++i)
System.out.println(results.get(i));
}
}

Related

ArrayList and Passing values

I am new to programming and we just learned ArrayLists in my class today and I have an easy question for you guys, I just can't seem to find it in the notes on what to set the passing value equal to. The point of this practice program is to take in a Number Object (that class has already been created) and those Numbers in the ArrayList are supposed to be counted as odds, evens, and perfect numbers. Here is the first couple of lines of the program which is all you should need.
import java.util.ArrayList;
import static java.lang.System.*;
public class NumberAnalyzer {
private ArrayList<Number> list;
public NumberAnalyzer() {
list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
}
public void setList(String numbers) {
}
What am I supposed to set (String numbers) to in both NumberAnalyzer() and setList()? Thanks in advance for answering a noob question!
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
This is the Lab16b Class that will run the program. ^^
public class Number
{
private Integer number;
public Number()
{
number = 0;
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return 0;
}
public boolean isOdd()
{
return number % 2 != 0;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++)
{
if(number % i == 0)
{
total = total + i;
}
}
if(total == number)
{
return true;
}
else
{
return false;
}
}
public String toString( )
{
return "";
}
}
Here is the Number class. ^^
Based on the information you provided, this is what I feel NumberAnalyzer should look like. The setList function is presently being used to take a String and add the numbers in it to a new list.
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer() {
this.list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
setList(numbers);
}
public void setList(String numbers) {
String[] nums = numbers.split(" ");
this.list = new ArrayList<Number>();
for(String num: nums)
list.add(new Number(Integer.parseInt(num)));
}
}
Analyze to learn something.
public static void main(String[] args) {
String temp = "5 12 9 6 1 4 8 6";
NumberAnalyzer analyzer = new NumberAnalyzer(temp);
//foreach without lambda expressions
System.out.println("without Lambda");
for (NeverNumber i : analyzer.getList()) {
i.print();
}
//with the use of lambda expressions, which was introduced in Java 8
System.out.println("\nwith Lambda");
analyzer.getList().stream().forEach((noNumber) -> noNumber.print());
NeverNumber number = new NeverNumber(31);
number.print();
number.setNumber(1234);
number.print();
}
public class NumberAnalyzer {
private List<NeverNumber> list; //List is interface for ArrayList
public NumberAnalyzer(String numbers) {
String[] numb=numbers.split(" ");
this.list=new ArrayList<>();
for (String i : numb) {
list.add(new NeverNumber(Integer.parseInt(i)));
}
}
public void setList(List<NeverNumber> numbers) {
List<NeverNumber> copy=new ArrayList<>();
numbers.stream().forEach((i) -> {
copy.add(i.copy());
});
this.list=copy;
}
public List<NeverNumber> getList() {
List<NeverNumber> copy=new ArrayList<>();
this.list.stream().forEach((i) -> {
copy.add(i.copy());
});
return copy;
}
public NeverNumber getNumber(int index) {
return list.get(index).copy();
}
}
public class NeverNumber { //We do not use the names used in the standard library.
//In the library there is a class Number.
private int number; // If you can use simple types int instead of Integer.
public NeverNumber() {
number = 0;
}
public NeverNumber(int num) {
number = num;
}
private NeverNumber(NeverNumber nn) {
this.number=nn.number;
}
public void setNumber(int num) {
number = num;
}
public int getNumber() {
return this.number;
}
public boolean isOdd() {
return number % 2 != 0;
}
public boolean isPerfect() {
long end = Math.round(Math.sqrt(number)); //Method Math.sqrt(Number) returns a double, a method Math.round(double) returns long.
for (int i = 2; i < end + 1; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public NeverNumber copy(){
return new NeverNumber(this);
}
public void print() {
System.out.println("for: " + this.toString() + " isPer: " + this.isPerfect() + " isOdd: " + this.isOdd() + "\n");
}
#Override //Every class in Java inherits from the Object class in which it is toString(),
//so we have to override our implementation.
public String toString() {
return this.number + ""; //The object of any class + "" creates a new object of the String class,
//that is for complex types, calls the toString () method implemented in this class,
//override the toString () from the Object class. If the runs, we miss class toString()
//calls from the Object class.
}
}

ArrayList comparison

I have an ArrayList made out of classes objects .The class has several String fields . In some classes
some fields that are the same must be removed from the ArrayList .
The field from the class that I need to check is sorted_participants which is set to be the same in some objects.
This is my Class:
public class Neo4jCompensation {
private String number_of_participants;
private String amount;
private String sorted_participants;
private String unsorted_participants;
private String href_pdf_compensation;
private String signed_by_all;
public Neo4jCompensation() {
this.number_of_participants = "";
this.amount = "";
this.sorted_participants = "";
this.unsorted_participants = "";
this.href_pdf_compensation = "";
this.signed_by_all = "";
}
public String getNumber_of_participants() {
return number_of_participants;
}
public void setNumber_of_participants(String number_of_participants) {
this.number_of_participants = number_of_participants;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getSorted_participants() {
return sorted_participants;
}
public void setSorted_participants(String sorted_participants) {
this.sorted_participants = sorted_participants;
}
public String getUnsorted_participants() {
return unsorted_participants;
}
public void setUnsorted_participants(String unsorted_participants) {
this.unsorted_participants = unsorted_participants;
}
public String getHref_pdf_compensation() {
return href_pdf_compensation;
}
public void setHref_pdf_compensation(String href_pdf_compensation) {
this.href_pdf_compensation = href_pdf_compensation;
}
public String getSigned_by_all() {
return signed_by_all;
}
public void setSigned_by_all(String signed_by_all) {
this.signed_by_all = signed_by_all;
}
}
So I have a first list filled with Classes:
ArrayList<Neo4jCompensation> results_list=new ArrayList<Neo4jCompensation>();
I thought that very good way to find the duplicates is to make a copy of a list , compare the two for the same class fields values and remove the duplicates .
This is how I find the duplicates
ArrayList<Neo4jCompensation> results_list1=new ArrayList<Neo4jCompensation>();
for(Neo4jCompensation pp:results_list)
{
Neo4jCompensation ss=new Neo4jCompensation();
ss.setAmount(pp.getAmount());
ss.setHref_pdf_compensation(pp.getHref_pdf_compensation());
ss.setNumber_of_participants(pp.getNumber_of_participants());
ss.setSigned_by_all(pp.getSigned_by_all());
ss.setSorted_participants(pp.getSorted_participants());
ss.setUnsorted_participants(pp.getUnsorted_participants());
results_list1.add(ss);
}
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(i!=j)
{
String prvi=kk.getSorted_participants().trim();
String drugi=n2.getSorted_participants().trim();
if(prvi.equals(drugi))
{
// results_list1.remove(j);
out.println("<p> Are equal su :"+i+" i "+j+"</p>");
}
}
}
}
Since I know that I can not loop and remove the elements from the ArrayList at the same
time i tried to use iterators like this ...
int one=0;
int two=0;
Iterator<Neo4jCompensation> it = results_list.iterator();
while (it.hasNext()) {
Neo4jCompensation kk=it.next();
Iterator<Neo4jCompensation> it1 = results_list1.iterator();
while (it1.hasNext()) {
Neo4jCompensation kk1=it1.next();
String oo=kk.getSorted_participants().trim();
String pp=kk1.getSorted_participants().trim();
if(one<two && oo.equals(pp))
{
it1.remove();
}
two++;
}
one++;
}
But it fails and gives me back nothing in ArrayList results_list1 - before removal with iterator it has in it the right elements . How to remove the objects from the array list that have the same field values as some other objects in the ArrayList .
Why not use .removeAll()
results_list1.removeAll(resultList);
This will require you to implement equals and hashcode within Neo4jCompensation
public class Neo4jCompensation {
//Omitted Code
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((number_of_participants == null) ? 0
: number_of_participants.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Neo4jCompensation other = (Neo4jCompensation) obj;
if (number_of_participants == null) {
if (other.number_of_participants != null)
return false;
} else if (!number_of_participants.equals(other.number_of_participants))
return false;
return true;
}
}
Another approach could be:
Overrride equals method in your Neo4jCompensation and check for the sorted_participants and return accordingly. Then use Set as a collection of your objects. Set does not allow duplicates and it uses equals to determine the equality.
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(results_list1.contains(kk) { results_list1.remove(j); }
}
But you may want to use a Set instead of a List or a data structure that maintains order, like a SortedMap, with a sentinel value.

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

I'm using Eclipse and I'm using Java. My objective it's to sort a vector, with the bogoSort method
in one vector( vectorExample ) adapted to my type of vector and use the Java sort on other vector (javaVector) and compare them.
I did the tests but it did't work, so I don't know what is failing.
*Note: there are few words in spanish: ordenado = sorted, Ejemplo = Example, maximo = maximun, contenido = content.
EjemploVector class
package vector;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Iterator;
public class EjemploVector <T> {
protected T[] contenido;
private int numeroElementos;
#SuppressWarnings("unchecked")
public EjemploVector () {
contenido = (T[]) new Object[100];
numeroElementos = 0;
}
#SuppressWarnings("unchecked")
public EjemploVector (int maximo) {
contenido = (T[]) new Object[maximo];
numeroElementos = 0;
}
public String toString(){
String toString="[";
for (int k=0; k<numeroElementos;k++){
if (k==numeroElementos-1){
toString = toString + contenido[k].toString();
} else {
toString = toString + contenido[k].toString()+", ";
}
}
toString = toString + "]";
return toString;
}
public boolean equals (Object derecho){
if (!(derecho instanceof Vector<?>)) {
return false;
} else if (numeroElementos != ((Vector<?>)derecho).size()) {
return false;
} else {
Iterator<?> elemento = ((Vector<?>)derecho).iterator();
for (int k=0; k<numeroElementos;k++){
if (!((contenido[k]).equals (elemento.next()))) {
return false;
}
}
return true;
}
}
public void addElement (T elemento){
contenido[numeroElementos++]= elemento;
}
protected T[] getContenido(){
return this.contenido;
}
protected T getContenido (int k){
return this.contenido[k];
}
#SuppressWarnings("unchecked")
protected void setContenido (int k, Object elemento){
this.contenido[k]= (T)elemento;
}
EjemploVectorOrdenadoClass
package vector.ordenado;
import java.util.Arrays;
import java.util.Random;
import vector.EjemploVector;
public class EjemploVectorOrdenado<T extends Comparable<T>> extends EjemploVector<T> {
private boolean organized;
public EjemploVectorOrdenado() {
super();
organized = true;
}
public EjemploVectorOrdenado(int maximo) {
super(maximo);
organized = true; //
}
public boolean getOrdenado() {
return this.organized;
}
// Method bogoSort
public void bogoSort() {
if (!this.organized) {
if (this.size() > 0) {
Random generator;
T tempVariable;
int randomPosition;
do {
generator = new Random();
for (int i = 0; i < this.size(); i++) {
randomPosition = generator.nextInt(this.size());
tempVariable = contenido[i];
contenido[i] = contenido[randomPosition];
contenido[randomPosition] = tempVariable;
}
} while (!organized);
}
}
this.organized = true;
}
public void addElement(T elemento) {
super.addElement(elemento);
if (organized && this.size() > 1) {
T penultimo = this.getContenido(this.size() - 2);
T ultimo = this.getContenido(this.size() - 1);
organized = penultimo.compareTo(ultimo) <= 0;
}
}
}
ElementoTest class
package elementos;
import java.io.Serializable;
public class ElementoTest implements Comparable<ElementoTest>, Serializable {
private static final long serialVersionUID = -7683744298261205956L;
private static int numeroElementosTest = 0;
private int clave;
private int valor;
public ElementoTest(int i){
this.clave = i;
this.valor = numeroElementosTest;
numeroElementosTest++;
}
public String toString(){
return ("(" + this.clave + "," + this.valor + ")");
}
public boolean equals (Object derecho){
if (!(derecho instanceof ElementoTest)) {
return false;
} else {
return clave == ((ElementoTest)derecho).clave;
}
}
public char getClave(){
return this.clave;
}
public int getValor(){
return this.valor;
}
#Override
public int compareTo(ElementoTest elemento) {
if (elemento == null){
return -1;
} else if (this.equals(elemento)){
return 0;
} else if (clave < elemento.clave){
return -1;
} else {
return 1;
}
}
}
TESTS
The first it's a stupid test, because it puts elements in order so... really the methods arenĀ“t doing anything, java just compare and it gives correct
I tried to make an unsorted vector adding elements but there appears the java.lang.ClassCastException: [Ljava.... etc.
package vector.ordenado;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Vector;
import org.junit.Before;
import org.junit.Test;
import elementos.ElementoTest;
public class EjemploVectorOrdenadoTest {
private Vector<ElementoTest> vectorJava;
private EjemploVectorOrdenado<ElementoTest> vectorExample;
#Before
public void setUp() throws Exception {
vectorJava = new Vector<ElementoTest>(100);
vectorExample = new EjemploVectorOrdenado<ElementoTest>(100);
}
#Test
public void testSortFailTest() {
for (char c = 'a'; c < 'g'; c++) {
vectorJava.addElement(new ElementoTest(c));
vectorExample.addElement(new ElementoTest(c));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
#Test
public void testSort() {
{
vectorJava.addElement(new ElementoTest(1));
vectorJava.addElement(new ElementoTest(3));
vectorJava.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(3));
vectorExample.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(1));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
}
Sorry, for the problems and thanks.
The problem is that your test class ElementoTest should implement the Comparable interface. Or you need to provide a Comparator during your comparison.
Does your class ElementtoTest implement Comparable?
If not, it needs to.
I'm suspecting it doesn't, because that's exactly what would cause this error. you'll need to add implements Comparable and then override the int compareTo(Elementtotest e) method, where you specify what criteria you'd like to order the objects based on.

How do you use a separate class to determine a result?

my issue is in my "NumberAnalyzer.java" class, I'm supposed to be able to use the "Number.java" class to determine if a number from the ArrayList is odd (as well as even and perfect later on) but since the "isOdd()" method in "Number.java" doesn't read in an int or other variable itself, I can't find a way to test each number to make "oddCount" in the "countOdds" method of "NumberAnalyzer.java" increase to produce the number of odd numbers in the string from the runner class.
NumberAnalyzer.java
import java.util.ArrayList;
import java.util.Scanner;
import com.sun.xml.internal.ws.api.pipe.NextAction;
import static java.lang.System.*;
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer()
{
}
public NumberAnalyzer(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
System.out.println(list);
}
public void setList(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
}
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
public int countEvens()
{
int evenCount=0;
return evenCount;
}
public int countPerfects()
{
int perfectCount=0;
return perfectCount;
}
public String toString( )
{
return "";
}
}
Number.java
public class Number
{
private Integer number;
public Number()
{
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return number;
}
public boolean isOdd()
{
if(number%2==0){
return false;
}
return true;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++){
if(number%i==0){
total+= i;
}
}
return (number==total);
}
public String toString( )
{
String output = getNumber() + "\n" + getNumber()+ "isOdd == " + isOdd() + "\n" + getNumber()+ "isPerfect==" + isPerfect()+ "\n\n";
return output;
}
}
runner class
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;
public class Lab16b
{
public static void main( String args[] )
{
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
//add more test cases
}
}
When you call
test.countOdds());
control goes to NumberAnalyzer.java
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
And here you are calling Number.isOdd() method by Class name as a static way but i do not think you can do this way because isOdd() is not static.
It is compile time error
Solution:
Iterate your list and send value one by one from the list to isOdd(int val) method.
Try to make isOdd() method static which accept one numeric parameter and will return true or false.
increase your counter based on return type as you do.

Generic Class Iterator

I have three classes, those being Lister, ObjectSortedList and SortedListProgram. I'm having trouble with the iterator for the generic class. What am I doing wrong?
This is the error I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at objectsortedlist.ObjectSortedList.getData(ObjectSortedList.java:122)
at objectsortedlist.Lister.hasNext(Lister.java:28)
at objectsortedlist.SortedListProgram.main(SortedListProgram.java:52)
Java Result: 1
Here are my classes:
package objectsortedlist;
import java.util.Iterator;
/**
*
* #author Steven
*/
public class ObjectSortedList<T> implements Cloneable, Iterable<T> {
private T[] data;
private int capacity;
public ObjectSortedList()
{
final int init_capacity = 10;
capacity = 0;
data = (T[])new Object[init_capacity];
}
public ObjectSortedList(int init_capacity)
{
if(init_capacity < 0)
throw new IllegalArgumentException("Initial capacity is negative: " + init_capacity);
capacity = 0;
data = (T[])new Object[init_capacity];
}
private boolean empty()
{
if(data.length == 0 || data[0] == null)
return true;
else
return false;
}
public int length()
{
return capacity;
}
public void insert(T element)
{
if(capacity == data.length)
{
ensureCapacity(capacity * 2 + 1);
}
data[capacity] = element;
capacity++;
}
public boolean delete(T target)
{
int index;
if(target == null)
{
index = 0;
while((index < capacity) && (data[index] != null))
index++;
}
else
{
index = 0;
while((index < capacity) && (!target.equals(data[index])))
index++;
}
if(index == capacity)
return false;
else
{
capacity--;
data[index] = data[capacity];
data[capacity] = null;
return true;
}
}
private void ensureCapacity(int minCapacity)
{
T[] placeholder;
if(data.length < minCapacity)
{
placeholder = (T[])new Object[minCapacity];
System.arraycopy(data, 0, placeholder, 0, capacity);
data = placeholder;
}
}
public ObjectSortedList<T> clone()
{
// Cloning
ObjectSortedList<T> answer;
try
{
answer = (ObjectSortedList<T>) super.clone();
}
catch(CloneNotSupportedException cnse)
{
throw new RuntimeException("This class does not implement cloneable.");
}
answer.data = data.clone();
return answer;
}
#Override
public Iterator<T> iterator()
{
return (Iterator<T>) new Lister<T>(this, 0);
}
public T getData(int index)
{
return (T)data[index];
}
}
package objectsortedlist;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
*
* #author Steven
*/
public class Lister<T> implements Iterator<T>
{
private ObjectSortedList<T> current;
private int index;
public Lister(ObjectSortedList<T> top, int index)
{
current = top;
this.index = index;
}
#Override
public boolean hasNext()
{
return (current.getData(index) == null);
}
#Override
public T next()
{
T answer;
if(!hasNext())
throw new NoSuchElementException("The Lister is empty.");
answer = current.getData(index+1);
return answer;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Don't use this. Use objectsortedlist.SortedList.delete(T target).");
}
}
package objectsortedlist;
import java.util.Scanner;
/**
*
* #author Steven
*/
public class SortedListProgram {
private static Scanner scan = new Scanner(System.in);
private static String[] phraseArray = {"Hullabaloo!", "Jiggery pokery!", "Fantastic!", "Brilliant!", "Clever!", "Geronimo!", "Fish sticks and custard.", "Spoilers!",
"Exterminate!", "Delete!", "Wibbly-wobbly!", "Timey-wimey!"};
private static Lister<String> print;
public static void main(String args[])
{
int phraseNo = 0;
System.out.println("I'm gonna say some things at you, and you're going to like it."
+ " How many things would you like me to say to you? Put in an integer from 1-12, please.");
try
{
phraseNo = Integer.parseInt(scan.nextLine());
while((phraseNo < 1) || (phraseNo > 12))
{
System.out.println("The integer you entered wasn't between 1 and 12. Make it in between those numbers. Please? Pleaseeeee?");
phraseNo = Integer.parseInt(scan.nextLine());
}
}
catch(NumberFormatException nfe)
{
System.out.println("C'mon, why don't you follow directions?");
phraseNo = 0;
}
if(phraseNo == 0);
else
{
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
print = new Lister<String>(phrases, phraseNo);
while(print.hasNext())
System.out.println(print.next());
}
}
}
After looking at your code I found multiple issues, here are they:
In your SortedListProgram class, in following code the phrases.length() will be 0, so the it will never go in that loop.
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
Moreover in SortedListProgram class's this call sequence
print.hasNext() -> current.getData(index)
the index passed is equal to size of data array field in the
ObjectSortedList class and Since in java array indexes ranges from
zero to array size -1. So you are bound to get
java.lang.ArrayIndexOutOfBoundsException always.
Please correct your code.

Categories

Resources