Trying to access subclass methods - java

So i have an array called roster filled with both Pitchers and Batters and Players( the Player is the super-class of both pitchers and batters)
private Player[] roster;
roster[i] = new Pitcher();
How i would i access methods in the pitcher? For example:
public double calculateTeamERA()
{
double ERA = 0;
for(int i = 0; i < 25; i++)
{
if(roster[i] instanceof Pitcher)
{
ERA+= roster[i].calculateERA();
}
}
return ERA;
}
So i have a calculate method, and the method calculateERA() is correct syntax, i'm just wondering if there is a way to tell it to access the Pitcher object, because it gives me a syntax error there is no calculateERA() in the PLAYER method which there isn't it's in the pitcher method.

Actually found the answer! You have to type cast it and you have to obey the hierarchy so in my case it would be:
ERA+= ((Pitcher)roster[i]).calculateERA();

Related

Methods with multiple arguments iterating an array

I have this method here:
boolean exibirAprovacao(double[][] codigoAluno, double[] codigoMateria, double nota) {
boolean aprovaAluno = false;
for(int i = 0; i < materia.length; i++) {
materia[i] = codigoAluno;
for(int j = 0; j < materia[i].length; j++) {
materia[i][j] = codigoMateria;
for(int k =0; k < materia[i][j].length; k++) {
materia[i][j][k] = nota;
if(materia[i][j][k] > 7.0) {
aprovaAluno = true;
}
}
}
}
return aprovaAluno;
}
I'm supposed to call it giving three arguments, #1 student code, #2 subject code and #3 grade. I had declared them as "double" in the method, but Eclipse highlighted it as "cannot convert from double[] to double", so it suggested me to change from this:
boolean exibirAprovacao(double codigoAluno, double codigoMateria, double nota)
To this:
boolean exibirAprovacao(double[][] codigoAluno, double[] codigoMateria, double nota)
And now Eclipse gives me an error when I'm calling my method:
aluno01.exibirAprovacao(codigoAluno, codigoMateria, nota);
Stating that
the method arguments are not applicable to the ones I'm passing
This is my array declaration:
double[][][] materia = new double[3][1][1];
This is an assignment that I have (starting Java + OO now). Any feedback is really appreciated.
First, you must review the logic of your program: If the method is supposed to find out if a certain student of a certain grade has aproved a certain subject, it should search one single value into the materia multi-array. I insist: It must search for a value, not fill in the data.
Second: Based upon the same assumption, to perform such a search, it would be enough if the method received three single parameters.
If Eclipse suggest you to change any method's firm, first understand what is the cause of the error. And do not accept suggestions without being aware of the implications (In this case, I'm afraid you shouldn't have accepted).

Java: NPE calling a method on an array element

I'm having an issue when I want to set the name of an object to another class, because I keep receiving the NullPointerException, and I'm not quite sure how to fix this error.
Here is an example:
First Class:
//Just excuse the Vehicle class, it's just an example
private Vehicle[] car;
private int number = 1;
private int count = 0;
public store Display()
{
car = new Vehicle[number];
}
public void setVehicleName(String name)
{
car[count].setName(name);
}
public String getVehicleName()
{
return car[count].setName(name);
}
Second class:
//So, I have radio buttons, so I'll just skip to that code
if (addName.equals(e.getActionCommand()))
{
name = JOptionPane.showInputDialog(null, "Enter the vehicle name: "); //there is a private String name
name.toLowerCase(); //automatically converted to lower case
displayStore.setVehicleName(name); //assume an Display object called 'displayStore'
}
So, if anybody has an idea or know how's to fix it, I would be grateful. Thanks!
Arrays of objects in java come default set to null so if you do
Vehicle [] car = new Vehicle[number];
car[1].setName("Toyota");
You will get a NullPointerException because car[1] is null
You need to initialize the array. So likely you will want to do this in your constructor
public store Display()
{
car = new Vehicle[number];
for(int i=0;i<number;i++) {
car[i] = new Vehicle();
}
}
You need to instantiate car[count] before using it. So, replace your Display method with this:
public store Display()
{
car = new Vehicle[number];
for(int i = 0; i < count; i++)
car[i] = new Vehicle();
//Return some store type object here or change the type to void
// Moreover it is better to do initialization/instantiation in the constructor, rather
// than a separate method
}

improve calling next method in JAVA

I'm looking for a better way to organize my class.
Right now my code looks like this:
mainMethod:
-number1 input
-call method1 with number1 als value
method1:
-do "stuff" with input
-call method2 with new "stuff" as value
method2:
-do stuff
-call method3
etc...
So i start with user input in my main method and my whole class works like domino, the first method needs to be called to run the next method.
I would rather have method1 return a value and save it in some global variable in my class which can be used by method2 and so on.
Here is my Code with exactly this problem: (it calculates sqrt)
package wurzel;
import java.util.Scanner;
import wurzel.Fraction;
public class wurzel {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Eingabe:");
int in = s.nextInt();
s.close();
bisection(in);
}
private static int bisection(int N){
int counter = 0;
for(int i = 0; i < N;i++){
if((counter*counter) > N){
counter--;
break;
}
else if(counter*counter == N){
break;
}
else counter++;
}
calculateSequence(counter,N);
return counter;
}
static int[] calculateSequence(int vKomma, int look){
int m = 0;
int d = 1;
int a = vKomma;
int[] intarr = new int[4];
intarr[0] = vKomma;
for(int i = 1; i <= intarr.length; i++){
if(i == intarr.length )
break;
else{
m = (d*a) - m;
d = (look - (m*m)) / d;
a = (vKomma + m) / d;
intarr[i] = a;
}
}
calculateApproximation(intarr);
return intarr;
}
static double calculateApproximation(int[] sequence ){
Fraction result = new Fraction((sequence.length)-1);
for(int dcounter = sequence.length; dcounter > 0; dcounter--){
result = result.reciprocal().add(sequence[dcounter-1]);
}
System.out.println("Approximation als double: " +result.doubleValue());
System.out.println("Approximation als Bruch: " +result);
return result.doubleValue();
}
}
You should also seperate code into different classes. E.g. have a generic MathHelper class which has these methods in it.
This helps keep code seperate and easy to read.
You mentioned that you wanted to store some data in a global variable for the class as a whole. The way to do this is by making the class use instance methods rather than class methods. With class methods, you have to use class variables. But, when you use instance methods, you can define instance variables which can be accessed by any method within the class.
To do this, change all your methods (apart from main()) by removing the keyword static from each method. Then, define the instance variable that is global for the class. e.g. if your global variable is of type int then it would be:
private int myInstanceVariable;
This instance variable, or global variable, can be accessed by a getter and setter.
It is quite normal methods to call each other and to form long chains of calls.
So I would not worry about that. Actually in real world, in enterprise code,
you have call stack going through tens of calls. So I think global variables would
be worse practice compared to what you did.

Initialising/Creating Objects through a constructor

Ok so I'm doing an assignment for my java coursets part I'm stuck at is :
"Implement an operation createparliamentMembers which will create the particular Parliament
with 80 members."
So i've already created the constructor with it's methods. This is how I wrote the operation to create the objects using the constructor.:
public static void createparliamentMembers(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
The problem is the arrays and objects only seem to exist in the operation for creating them and when I try running method of the objects created they don't work because the driver class doesn't recognize the arrays. On the other hand when I use this as just a normal part of the Driver for it runs fine and all methods of the objects work normally.
Edit: Ok so I'm still getting the same problem as before even though i initiliased them outside the createparliamentMembers();
The following code is the Driver im using to test the methods: It keeps saying there is a:
Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:11)
which is the code array[1].FlipCoin(); as im trying to use the method flipcoin from the created objects but it's not working.
public static void main(String [] args) {
Commands.createparliamentMembers();
array[1].FlipCoin();
}
Your arrays are only defined locally, which means they live and die with the method. When your method finishes, they get put out of memory.
The solution is to define these arrays as instance variables. By that I mean, you need to define the arrays for your class, and then use them in your method:
class someClass {
int[] myArray = new int[2];
private void someMethod() {
myArray[0] = 3;
myArray[1] = //whatever
}
}
You state in comment:
I do have a parliament class it's on it own and contains the methods and constructor for the members of the parliament. The above method was in a seprate class called Commands. I don't understand completely the "Can you add the members to a Parliament object as you create them?" The parliament isn't an object more se then a class containing a constructor and methods for parliament members i want to create.
Parliament isn't an object yet, but you should in fact create one, and in fact your instructions tell you just that: "which will create the particular Parliament with 80 members...". You will need to tell us more about your program's structure and your specific requirements, but I suggest:
First create a Parliament object in the createParliamentMembers method, and call it parliament.
Then create the members of parliament in that method.
As you create these members, add them to the Parliament object, parliament.
At the end of the method return the parliament variable.
This means that your createParliamentMembers method's signature must change so that rather than return void it should be written to return a Parliament object.
When calling the method in the main method, assign what it returns to a Parliament variable that is in the main method.
It looks like you are writing a factory method. Create a constructor for Parliament like this:
public Parliament(Member[] members, Legislator[] legislators, Leader[] leaders) {
// do whatever with what's passed in
}
Then change your method to return a Parliament object and in the method pass your initialized arrays into the Parliament constructor, like this:
// same code as your except the last line
public static Parliament createParliament(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
return new Parliament(array, leg, lead);
}

Using Array of Objects in Parameters, Inheritance in Parameters

I have the class Building and the sub-classes Barracks and House. Now I have an array of houses and barracks defined like this:
public House[] arrSHouse;
public Barracks[] arrBarr;
Now my code is designed such that I when I want to create a house, a house will follow my mouse in the applet. This way works:
for(int h = 0; h < arrSHouse.length; h ++)
{
if(arrSHouse[h].held == true)
{
arrSHouse[h].isAlive = true;
arrSHouse[h].xpos = e.getX()-8;
arrSHouse[h].ypos = e.getY()-20;
}
}
However, I want to make my code more efficient by making a method that will allow me to input an array, such as arrBarr, which is an array of Barracks, and do the same things as the method shown above. This is my attempt:
public void buildingFollowMouse(Building[]type, MouseEvent e)
{
for(int a = 0; a < type.length; a ++)
{
if(type[a].held == true)
{
type[a].isAlive = true;
type[a].xpos = e.getX()-8;
type[a].ypos = e.getY()-20;
}
}
}
However, this doesn't work. The only way that this works is if I say:
public void buildingFollowMouse(House[]type, MouseEvent e)
as the parameters and say:
buildingFollowMouse(arrSHouse, e);
This of course would mean writing another method for the barracks method.
I just want to know a way that I can input a sub-class of Building in my parameter and have it work the same way that it worked above with the House for-loop with any other Building I decide to make. How can I do this?

Categories