why can't I use parent method? (ArrayList) - java

everybody
I have some questions~
In the main method , int size = s.getSize()
but when I change to int size = s.size()
Why compiler show NoSuchMethodError?
Mystack is a ArrayList's child class
Why can't I use size() method?
package ch11;
import java.util.ArrayList;
import java.util.Scanner;
public class ch11_10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MyStack s = getStack(input);
int size = s.getSize();//換成s.size()
for (int i = 0; i < size; i++) {
System.out.println(s.pop());
}
}
public static MyStack getStack(Scanner input) {
System.out.print("Enter five strings: ");
MyStack s = new MyStack();
for (int i = 0; i < 5; i++) {
s.push(input.next());
}
return s;
}
}
class MyStack extends ArrayList {
public int getSize() {
return size();
}
public Object peek() {
return get(size() - 1);
}
public Object pop() {
Object o = get(size() - 1);
remove(size() - 1);
return o;
}
public void push(Object o) {
add(o);
}
#Override
public String toString() {
return "stack: " + toString();
}
}

Related

Sorting an ArrayList of Names using a Comparator that sorts by length

I'm having trouble with my code. I tried using Strings for the arraylist but it doesn't work. When I put the class name in the arraylist, it only prints a different value. I made a class to get the length because doing it in the comparator didn't work; it just gives me a cannot find symbol error.
import java.util.*;
import java.io.*;
class StringLengthComparator implements Comparator<Name>
{
public int compare(Name n1, Name n2)
{
return n1.getLength()-n2.getLength();
}
}
public class Name implements Comparable<Name>
{
public static String name;
public Name(String n)
{
this.name = n;
}
public int compareTo(Name that)
{
return this.name.compareTo(that.name);
}
public String getName()
{
return this.name;
}
public int getLength()
{
return this.name.length();
}
public static void main(String[] args) throws Exception
{
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
//String n = keyIn.readLine();
for(int i=0;i<5;i++)
{
String n = keyIn.readLine();
N.add(new Name(n));
}
System.out.print("\n");
Collections.sort(N);
for(int i=0;i<N.size();i++)
{
System.out.println(N.get(i));
}
System.out.print("\n");
Collections.sort(N, new StringLengthComparator());
for(int i=0;i<N.size();i++)
{
System.out.println(N.get(i));
}
}
}
Error #1 for ArrayList<\String> N = new ArrayList<\String>
Error #2 for ArrayList <\Name> N = new ArrayList<>(5)
If you want to sort by length and alphabetically by choice you need 2 comperators and choose each time which one to use, by N.sort(new X), where X is the name of the comperator class you want.
You don't need Collections.sort():
class StringLengthComparator implements Comparator<Name> {
public int compare(Name n1, Name n2) {
return n1.getLength()-n2.getLength();
}
}
class StringCommonComparator implements Comparator<Name> {
public int compare(Name n1, Name n2) {
return n1.getName().compareTo(n2.getName());
}
}
public class Name {
private String name;
public Name(String n) {
this.name = n;
}
public String getName() {
return this.name;
}
public int getLength() {
return this.name.length();
}
public static void main(String[] args) throws Exception {
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
String n = keyIn.readLine();
N.add(new Name(n));
for(int i=0; i<5; i++) {
String name = keyIn.readLine();
N.add(new Name(name));
}
System.out.println();
System.out.println("Compare by Length");
N.sort(new StringLengthComparator());
for(int i=0;i<N.size();i++) {
System.out.println(N.get(i).name);
}
System.out.println();
System.out.println("Compare by String");
N.sort(new StringCommonComparator());
for(int i=0;i<N.size();i++) {
System.out.println(N.get(i).name);
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class StringLengthComparator implements Comparator<Name> {
#Override
public int compare(Name n1, Name n2) {
return n1.getLength() - n2.getLength();
}
}
public class Name implements Comparable<Name> {
public static String name;
public Name(String n) {
this.name = n;
}
#Override
public int compareTo(Name that) {
return this.name.compareTo(that.name);
}
public String getName() {
return this.name;
}
public int getLength() {
return this.name.length();
}
public static void main(String[] args) throws Exception {
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
for (int i = 0; i < 5; i++) {
String n = keyIn.readLine();
N.add(new Name(n));
}
System.out.print("\n");
Collections.sort(N);
for (Name name : N) {
System.out.println(name.getName());
}
System.out.print("\n");
Collections.sort(N, new StringLengthComparator());
for (int i = 0; i < N.size(); i++) {
System.out.println(N.get(i));
}
}
}

Iterating over object of the class

In the following code, I instantiated an object of the class and wondering whether I am heading in the right direction or not?. Since it's not a collection, is there a way I can iterate through the items I am inserting using stack class object? Or is there something wrong with the solution design part?
package stack;
import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQPartII {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public int pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
} else {
int pop = q1.remove();
return pop;
}
}
public void push(int data) {
if (q1.peek() == null) {
q1.add(data);
} else {
for (int i = q1.size(); i > 0; i--) {
q2.add(q1.remove());
}
q1.add(data);
for (int j = q2.size(); j > 0; j--) {
q1.add(q2.remove());
}
}
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII ();
st.push(2);
}
}
You can make the class enclosing your stack implementation return an iterator() to iterate over the elements in the queue. The iterator() functionality can simply be delegated to the underlying container class holding the stack elements.
public class StackUsingQPartII implements Iterable<Integer>{
#Override
public Iterator<Integer> iterator() {
return q1.iterator();
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII();
st.push(2);
Iterator<Integer> it = st.iterator();
while (it.hasNext()) {
Integer i = it.next();
System.out.println(i);
}
}
}

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