Getting max value from object in an abstract class array [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I´ve been trying to solve this.
I wanted to get max ClassA value.
So I have an interface and 2 classes
public interface Something {
}
public class ClassA implements Something{
private int a;
public ClassA(int a) {
this.a = a;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
public class ClassB implements Something{
private int b;
public ClassB(int b) {
this.b = b;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
public class Program {
public static void main(String[] args) {
Something[] array = new Something[10];
array[0] = new ClassA(1);
array[1] = new ClassA(2);
array[2] = new ClassB(0);
ClassA max = null;
for (int i = 0; i < array.length; i++) {
if(array[i]!=null && array[i] instanceof ClassA){
//what do to here
}
}
}
}
I thought that I put this there,
if(array[i].getClassA()>max.getClassA()){
max = array[i];
}
but its not working, so what should I do to make it working ?
Thanks for answers.

I am guessing the code doesn't even compile. This is because it is not enough to determine an object is a type, you have to cast the reference to access it's methods or fields.
ClassA a = (ClassA) array[i];
if (a.getA() > max.getA())
max = a;
BTW This is not an example of Polymorphism as you are not using an overridden method here.
An example using polymorphism might look like
interface Something {
boolean isA();
int getA();
}
class ClassA implements Something {
// fields and constructor
public boolean isA() { return true; }
public int getA() { return a; }
}
Something[] array = { new ClassA(1), new ClassA(2), new ClassB(0) };
ClassA max = null;
for (Something s : array) {
if (s.isA()) {
if (max == null || max.getA() < s.getA())
max = s;
}
}

Do a null check on max and then compare the values
for (int i = 0; i < array.length; i++)
{
if(array[i]!=null && array[i] instanceof ClassA){
if (max == null || array[i].getA() > max.getA()){
max = array[i];
}
}
}

Related

I want to make this generic [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 days ago.
Improve this question
So I have written this code that works just fine with integers. Now I want to make it generic (extends Number), but keep it an array.
import java.util.Arrays;
public class StudentGrades {
private int grades[];
private int pointer;
private int max_grade;
private int min_grade;
private double average_grade;
private int better_than_average;
private int worse_than_average;
private int excelent_count;
private int good_count;
private int enaught_count;
public int getMax_grade() {
return max_grade;
}
public int getMin_grade() {
return min_grade;
}
public double getAverage_grade() {
return average_grade;
}
public int getBetter_than_average() {
return better_than_average;
}
public int getWorse_than_average() {
return worse_than_average;
}
public int getExcelent_count() {
return excelent_count;
}
public int getGood_count() {
return good_count;
}
public int getEnough_count() {
return enaught_count;
}
StudentGrades()
{
pointer=-1;
grades=new int[1000];
average_grade=0;
better_than_average=0;
worse_than_average=0;
excelent_count=0;
good_count=0;
enaught_count=0;
max_grade=0;
min_grade=0;
}
private void calculate()
{
average_grade=0;
better_than_average=0;
worse_than_average=0;
excelent_count=0;
good_count=0;
enaught_count=0;
max_grade=0;
min_grade=0;
if (pointer<0)return;
double sum=0;
max_grade=grades[0];
min_grade=grades[0];
for (int i=0; i<=pointer;i++)
{
sum+=grades[i];
if(grades[i]>max_grade)
max_grade=grades[i];
if(grades[i]<min_grade)
min_grade=grades[i];
if(grades[i]>=91)
excelent_count++;
else if(grades[i]>=71)
good_count++;
else if (grades[i]>=60)
enaught_count++;
}
average_grade=sum/(double) (pointer+1);
for(int i=0; i<=pointer;i++)
{
if(grades[i]>average_grade)
better_than_average++;
else
worse_than_average++;
}
}
private boolean is_valid(int n)
{
return (n>0 && n<100);
}
public boolean setter( int marks[])
{
for(int i=0; i<marks.length; i++)
{
if(!is_valid(marks[i]))
return false;
}
grades=marks;
pointer=marks.length-1;
calculate();
return true;
}
public boolean adder(int new_element)
{
if(!is_valid(new_element))
return false;
if(grades.length==pointer+1)
{
int[] new_size_array =new int[grades.length*2];
for(int i=0; i<=pointer;i++) new_size_array[i]=grades[i];
grades=new_size_array;
}
pointer++;
grades[pointer]=new_element;
calculate();
return true;
}
public int[] getter()
{
int[] result = new int[pointer+1];
for (int i=0; i<=pointer;i++)
result[i]=grades[i];
return result;
}
public void to_string(){
System.out.println(Arrays.toString(getter()));
}
}
I have done this, but I strongly believe it is completely wrong and Im moving in the wrong direction. Im relatively new to programming, so please make your explanations as detailed as possible. Thamks!
import java.util.Arrays;
import java.lang.reflect.Array;
public class StudentGradesGeneric <E extends Comparable<E>> extends Number{
public StudentGradesGeneric(Class<E> clazz, int capacity) {
grades = (E[]) Array.newInstance(clazz, capacity);
}
private E[] grades;
private int pointer;
private E max_grade;
private E min_grade;
private E average_grade;
private E better_than_average;
private E worse_than_average;
private E excelent_count;
private E good_count;
private E enaught_count;
public E getMax_grade() {
return max_grade;
}
public E getMin_grade() {
return min_grade;
}
public E getAverage_grade() {
return average_grade;
}
public E getBetter_than_average() {
return better_than_average;
}
public E getWorse_than_average() {
return worse_than_average;
}
public E getExcelent_count() {
return excelent_count;
}
public E getGood_count() {
return good_count;
}
public E getEnough_count() {
return enaught_count;
}
StudentGradesGeneric()
{
pointer=-1;
grades= (E[]) new Comparable[1000];
average_grade=null;
better_than_average=null;
worse_than_average=null;
excelent_count=null;
good_count=null;
enaught_count=null;
max_grade=null;
min_grade=null;
}
#Override
public int intValue() {
return 0;
}
#Override
public long longValue() {
return 0;
}
#Override
public float floatValue() {
return 0;
}
#Override
public double doubleValue() {
return 0;
}
private <E> void calculate()
{
average_grade=null;
better_than_average=null;
worse_than_average=null;
excelent_count=null;
good_count=null;
enaught_count=null;
max_grade=null;
min_grade=null;
if (pointer<0)return;
E sum=null;
max_grade=grades[0];
min_grade=grades[0];
for (int i=0; i<=pointer;i++)
{
sum =grades[i] + sum;
if ( grades[i].compareTo(max_grade) > 0)
max_grade=grades[i];
if(grades[i].compareTo(min_grade) < 0)
min_grade=grades[i];
if(grades[i].compareTo(91) >= 0)
excelent_count++;
else if(grades[i]>=71)
good_count++;
else if (grades[i]>=60)
enaught_count++;
}
average_grade=sum/ (pointer+1);
for(int i=0; i<=pointer;i++)
{
if(grades[i]>average_grade)
better_than_average++;
else
worse_than_average++;
}
}
private boolean is_valid(E n)
{
return (n>0 && n<100);
}
public boolean setter( E marks[])
{
for(int i=0; i<marks.length; i++)
{
if(!is_valid(marks[i]))
return false;
}
grades=marks;
pointer=marks.length-1;
calculate();
return true;
}
public boolean adder(E new_element)
{
if(!is_valid(new_element))
return false;
if(grades.length==pointer+1)
{
E[] new_size_array =(E[]) new Comparable[grades.length*2];
for(int i=0; i<=pointer;i++)
new_size_array[i]=grades[i];
grades=new_size_array;
}
pointer++;
grades[pointer]=new_element;
calculate();
return true;
}
public E[] getter()
{
E[] result = (E[]) new Comparable[pointer+1];
for (int i=0; i<=pointer;i++)
result[i]=grades[i];
return result;
}
public void to_string(){
System.out.println(Arrays.toString(getter()));
}
}
The problem is almost certainly this definition:
public class StudentGradesGeneric <E extends Comparable<E>> extends Number
This defines a new class named StudentGradesGeneric with a type argument named E that is required to extend Comparable<E>. StudentGradesGeneric also extends Number.
That last part is wrong: there's no reason for StudentGradesGeneric itself to extend Number (it's conceivable that someone would want that, but it'd be unlikely and nothing in your question indicates you do).
What you want is E to extend Number:
public class StudentGradesGeneric <E extends Number & Comparable<E>>
I've not checked the rest of your code and I think you'll find that Number is not as useful a base type as you'd wish, as there's no way, for example to add two generic Number objects and get an object of the same type back.

Cannot pass random enum value to function in Java

Cheers, I am pretty new to java and I and I have ran across a problem
I have three classes, all inheriting things between them. Starting I have a class A:
public class A{
private int index;
public A(int index) {
System.out.println("Creating an instance of A");
this.index = index;
}
}
then I have a sublass of A, class M which has a enum inside as:
public class M extends A{
public enum Letter {
A,B,C;
}
private Letter letter;
public M(int index, Letter aLetter) {
super(index);
System.out.println("Creating an instance of M");
this.letter = aLetter;
}
}
and finally a last class P , subclass of M:
public class P extends M {
private T t;
public enum T{
o,
a,
t
}
public P(int index, Letter aLetter, T aT) {
super(index,aLetter);
System.out.println("Creating an instance of P");
this.t = aT;
}
}
What I want to do is create e.g. 3 objects of the class P, and pass on to them RANDOMLY a value of each of these enums. I thought of creating a function in the main class which would be kind of like:
Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
my main looks like this:
int N = 3;
M[] new_m = new M[N]
for(int i = 0; i < N; i++) {
new_m[i] = new P(i, getRandLetter(), getRandT());
}
however I get this error: Cannot make a static reference to the non-static method . What Can I do to achieve what I want?
The error is telling what to do:
Cannot make a static reference to the non-static method
Your main method is static, and the methods called from it should be static as well. So your getRandLetter() and getRandT() methods should be static.
getRandLetter() should look like this:
static Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
And getRandT() should be static as well.

relation between two classes (german code) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want to make an array with which I can create some instances of the class Schiff (Ship) by using the class Flotte (Armada). Somehow it does not work. Which method is more useful? addShiff or addSchiff2?
public class Schiff
{
private String material;
private int kanonen;
private int ursprungsMäste;
private int mästeStehenNoch;
public Schiff (String material, int kanonen, int mäste)
{
this.material = material;
this.kanonen = kanonen;
ursprungsMäste = mäste;
mästeStehenNoch = mäste;
}
public String gibMaterial()
{
return material;
}
public void mastGetroffen(int wieVieleTreffer)
{
mästeStehenNoch = mästeStehenNoch - wieVieleTreffer;
}
public void wieVieleMäste ()
{
System.out.println("Es stehen noch " + mästeStehenNoch + " Mäste!");
}
}
+++++++
public class Flotte
{
private Schiff [] flottenArray;
public Flotte ()
{
flottenArray = new Schiff [100];
}
public void addSchiff (String material, int kanonen, int ursprungsMäste)
{
for (int zahl = 0; zahl<flottenArray.length; zahl++)
{
if (flottenArray[zahl] == null)
{
flottenArray[zahl] = new Schiff (material, kanonen, ursprungsMäste);
}
}
}
public void addSchiff2 (Schiff neuesSchiff)
{
for (int zahl = 0; zahl<flottenArray.length; zahl++)
{
if (flottenArray[zahl] == null)
{
flottenArray[zahl] = neuesSchiff;
}
}
}
public void gegnerischerFeuerAngriff ()
{
for (Schiff schiff : flotte)
{
if (schiff.gibMaterial().equals("holz"))
{
flottenArray.remove(schiff);
}
}
}
}
What exactly does not work?
Looks good to me.
My feeling is that you can drop the addSchiff (String material, int kanonen, int ursprungsMäste) method because:
One: It is just another way of writing addSchiff2(new Schiff(material, kanonen, ursprungsMäste)) and this is also how it should be coded to avoid repeating yourself:
public void addSchiff (String material, int kanonen, int ursprungsMäste)
{
addSchiff2(new Schiff(material, kanonen, ursprungsMäste))
}
Two: If you later decide to add fields to class Schiff you will have to change the interface of Flotte if you keep the method that constructs a Schiff instance from passed parameters. This is not the case if you just have a method that takes a Schiff instance. So getting rid of addSchiff() decreased inter-class coupling, which is gut.
Klar zur Halse!

I can't call a method in the client from my LinkedList class [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
got it working, see comments.
well apparently it's not just in the client. I can't call any of the methods I've created at all. For my assignment, I'm supposed to create those methods in a class then implement them in a client. I can't even call the methods within the initial class. Not sure why.
import java.util.*;
public class Driver5
{
public static final int SENTINEL = 0;
public static void main(String[] args)
{
int value = 1;
Scanner keyboard = new Scanner(System.in);
LinkedList<Intcoll5> P = new LinkedList<Intcoll5>();
while(value != SENTINEL)
{
if (value > 0)
{
P.**insert**(value);
}
}
}
}
still working on some methods, just trying to call insert()
import java.util.LinkedList;
import java.util.*;
public class Intcoll5
{
LinkedList<Integer> c = new LinkedList<Integer>();
ListIterator<Integer> I = c.listIterator();
public Intcoll5(int i)
{
c = new LinkedList<Integer>();
}
public void insert(int i)
{
Integer I = new Integer(i);
if (!c.contains(I))
{
c.addFirst(I);
}
}
public void copy(Intcoll5 obj)
{
while (I.hasNext())
{
}
}
public boolean belongs(Integer i)
{
return true;
}
public void omit(Integer i)
{
if (c.contains(i))
{
c.remove(i);
}
}
public int get_howmany()
{
int i = 0;
while (I.hasNext())
{
i++;
}
return i;
}
public void print()
{
while (I.hasNext())
{
Integer n = I.next();
System.out.println(n.intValue());
}
}
public boolean equals(Intcoll5 obj)
{
return true;
}
}
just "insert" is underlined in the client, error is: "cannot find symbol".
There is no insert method in the LinkedList class.
Just use add.
if (value > 0) {
Intcoll5 object = new Intcall5();
object.insert(value);
P.add(object);
}
I believe you're trying to invoke the Intcoll5#insert() method, but for this you will need to refer an instance of the Incoll5 class. Note that your P object refers a LinkedList.
Also, the constructor of the Intcoll5 class seem pretty weird to me, since it doesn't use it's i parameter. Change it to:
public Intcoll5()
{
c = new LinkedList<Integer>();
}

How to make a function inside a class mutuable?

Imagine I have a class
class A {
int a;
int b;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
return 0;
}
void setTheFunction([...]) {
[...]
}
}
And for every new object I instantiate, I want to be able to define theFunction() in a new way by calling setTheFunction( [...] ). For example, I want to do something like this:
A test = new A(3,2);
test.setTheFunction ( int x = a*b; return x*x+2; );
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
Or something like this:
A test2 = new A(1,5);
test.setTheFunction ( for(int i=0; i<b; i++) a=a*b*i; return a; );
Now, what I could of course do is write all of those functions inside class A and use a switch statement to determine which one is to pick. But if I don't want the algorithm of theFunction() hardcoded inside my class A, is there any way to do something similar to the above? And what would setTheFunction() look like? What type of argument would you have to pass?
You can use Callable.
public class A<V> {
public int a;
public int b;
private Callable<V> callable;
public A(int a, int b) {
this.a = a;
this.b = b;
}
public V theFunction() {
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setTheFunction(Callable<V> callable) {
this.callable = callable;
}
}
Then, to use it:
final A<Integer> test = new A<Integer>(3, 2);
test.setTheFunction(new Callable<Integer>() {
int x = test.a * test.b;
return x * x + 2;
});
System.out.println(test.theFunction());
Of course, the generic typing of A isn't necessary, but I've added it to make this answer to be less restricted.
If you always need to operate on the same arguments, you could solve this by defining an interface such as:
public interface MethodPerformer {
int performOperation(int a, int b);
}
Then pass in implementations of this to your setTheFunction method. Finally, invoke the operation when you call the other method:
class A {
int a;
int b;
MethodPerformer performer;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
performer.performOperation(a, b);
}
void setTheFunction(MethodPerformer performer) {
this.performer = performer;
}
}
Clearly additional code would be required to check the performer is not null. Perhaps take a performer in the constructor?
Instead of using a setter, the more natural way is to use an anonymous sub-class. This way the compiler will check it behaves correctly and has access to the right variables.
public class Main {
static abstract class A {
protected int a, b;
A(int a, int b) {
this.a = a;
this.b = b;
}
public abstract int theFunction();
}
public static void main(String... ignored) {
A test = new A(3, 2) {
#Override
public int theFunction() {
int x = a * b;
return x * x + 2;
}
};
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
A test2 = new A(1, 5) {
#Override
public int theFunction() {
for (int i = 1; i < b; i++) a = a * b * i;
return a;
}
};
System.out.println(test2.theFunction());
}
}
prints
38
15000
With this you can solve any kind of problem, that involves any kind of public variable of A (but can work with package private variables as well, if the AFunction implementation resides in the same package), that a function may use to perform it's operation. It's just not as compact as it can be in other languages than java.
interface AFunction
{
int call(A a);
}
class A
{
int a;
int b;
//giving it a default implementation
private AFunction f = new AFunction()
{
#Override
public int call(A a)
{
return a.a * a.b;
}
};
A(int a, int b)
{
this.a = a;
this.b = b;
}
int theFunction()
{
return f.call(this);
}
void setTheFunction(AFunction f)
{
this.f = f;
}
}
By the way as AlexTheo points out, all answers so far (except for Peter Lawrey's) are a form of the strategy design pattern.
The easiest way to do this is defining "A" as an interface instead of a class. You declare theFunction() without actually implementing it.
In client code, everytime you need "A", you instantiate a so-called anonymous inner class.
For example:
new A() { #Override public int theFunction() { ...your implementation... } };

Categories

Resources