Junit - Testing constructor without parameters? - java

I have to create JUnit test cases for this class. One of the tests is to test the constructor of the ShannonsTheorem class. Are there ways to test a constructor that does not have any parameters?
There is another class named ShannonsModel that also needs to have its constructor tested. According to the UML we were provided there are no parameters on that constructor either.
Thanks!
package network;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ShannonsTheorem {
ShannonsModel model = new ShannonsModel();
Scanner kb = new Scanner(System.in);
/**
* default constructor for ShannonsTheorem class.
*
*/
public ShannonsTheorem()
{
}
/**
* Method to return the value in bandwidth variable.
* #return
*/
public double getBandwidth()
{
return model.getBandwidth();
}
/**
* getSignalToNoise method to return the signalToNoise value in variable signalToNoise
* #return
*/
public double getSignalToNoise()
{
return model.getSignalToNoise();
}
/**
* main method for ShannonsTheorem
* #param args
* while loop to handle user input to continue or end program
*/
public static void main(String[] args)
{
try {
Scanner kb = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
ShannonsTheorem ST = new ShannonsTheorem();
System.out.println("Enter bandwidth in hertz:");
ST.setBandwidth(kb.nextDouble());
System.out.println("Enter signalToNoise:");
ST.setSignalToNoise(kb.nextDouble());
System.out.println("Values are:");
System.out.println("Bandwidth");
System.out.println(ST.getBandwidth());
System.out.println("SignalToNoise:");
System.out.println(ST.getSignalToNoise());
System.out.println(ST.maxiumumDataRate());
System.out.println("Press any key to make another calculation. Type N or n to Quit");
String s = scan.nextLine();
if(s.equals("n") || s.equals("N")) {
stop = true;
} // end of if
} // end of while loop
}catch (InputMismatchException e){
System.out.println("Input Exception was caught, restart program");
}catch(NumberFormatException e){
System.out.println("Format Exception was caught, restart program");
}
}
/**
* public method to retrieve the maximum data rate. This method makes a call to the private method
* under the same name.
* #return
*/
public double maxiumumDataRate()
{
// calling to the private method maxiumumDataRate. Storing the return value from said method into variable result
// when this public method is called it will return the result from the private method,
double result = model.maxiumumDataRate();
System.out.print(model.toString());
return result;
}
/**
* setBandwidth method to set the bandwidth value in hertz
* #param h
*/
public void setBandwidth(double h)
{
model.setBandwidth(h);
}
/**
* setSignalToNoise method to set the signalToNoise variable
* #param snr
*/
public void setSignalToNoise(double snr)
{
model.setSignalToNoise(snr);
}
}

Why do you need to test the constructor ?
You could test that without any modification, the default constructor has some specific fields :
#Test
public void shouldCreateADefaultShannonTheorem() {
ShannonsTheorem shannonsTheorem = new ShannonsTheorem();
Object expectedModel = new ShannonsModel();
assertEquals(expectedModel , shannonsTheorem.model);
Object expectedKb = new Scanner(System.in);
assertEquals(expectedKb , shannonsTheorem.kb);
}
or you could test that without any change, the default constructor gives you some results :
ShannonsTheorem shannonsTheorem = new ShannonsTheorem();
double expectedbandwith = 0.0;
assertEquals(expectedbandwith , shannonsTheorem.getBandwidth(), 0);
int expectedSignalToNoise = 0;
assertEquals(expectedSignalToNoise , shannonsTheorem.getSignalToNoise(), 0);
int expectedMaximumDataRate = 0;
assertEquals(expectedMaximumDataRate , shannonsTheorem.maxiumumDataRate(), 0);
// ...
that's why it is usefull to do TDD (test first) :
what your application should do ? write the test. // here is the thinking
write the code. // no thinking here !
refactor

Related

InputMismatchException when attempting to run program again in do while loop

Having successfully created a policy holder and writing the information to csv I try to run the program again using a do while loop but receive an inputmismatchexception after typing surname.
Can someone point me in the right direction or advise what I am doing wrong with this piece of code?
Here is example of what happens...
console
/**
*
*/
package InsurancePolicySystem;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* #author
*
*/
public class InsurancePolicy {
// create variables
private String surname;
private int age;
private String motorType;
private String motorPolicyId;
private String addAnother;
private String pattern = "^[a-zA-Z](\\s?[a-zA-Z]){2,29}$";
// import scanner for user input
Scanner scanner = new Scanner(System.in);
// time stamp number. -1 used on month as time stamp displays next year instead
// of current year
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH) - 1;
// sum of the year and month
int timeStamp = year + month;
/**
* default constructor
*/
public InsurancePolicy() {
}
/**
* non default constructor
*
* #param surname
* #param age
* #param motorType
* #param motorPolicyId
*/
public InsurancePolicy(String surname, int age, String motorType, String motorPolicyId) {
this.surname = surname;
this.age = age;
this.motorType = motorType;
this.motorPolicyId = motorPolicyId;
}
/**
*
* #return
*/
public String getSurname() {
return surname;
}
/**
* Surname should be more than 3 letters and not greater than 20. Anything more
* will cause a not valid error!
*
* #param surname
* #throws IllegalArgumentException
*/
public void setSurname(String surname) throws IllegalArgumentException {
this.surname = surname;
}
/**
*
* #return
*/
public int getAge() {
return age;
}
/**
* Age must be between 18 & 50 Any other age will produce not eligible error!
*
* #param age
* #throws IllegalArgumentException
*/
public void setAge(int age) throws IllegalArgumentException {
if ((age >= 18) && (age <= 50)) {
this.age = age;
} else {
throw new IllegalArgumentException("Not eligible for an insurance policy!");
}
}
/**
*
* #return
*/
public String getMotorType() {
return motorType;
}
/**
* motor type should only be either CAR, TAXI or BUS. if statement to prevent
* other vehicle types and throw error if user inputs a different vehicle.
*
* #param motorType
* #throws IllegalArgumentException
*/
public void setMotorType(String motorType) throws IllegalArgumentException {
if (motorType.equals("CAR") || motorType.equals("TAXI") || motorType.equals("BUS")) {
this.motorType = motorType;
} else {
throw new IllegalArgumentException("Not eligible for an insurance policy!");
}
this.motorType = motorType;
}
/**
*
* #return
*/
public String getMotorPolicyId() {
return motorPolicyId;
}
/**
*
* #param motorPolicyId
*/
public void setMotorPolicyId(String motorPolicyId) {
this.motorPolicyId = motorPolicyId;
}
/**
* Method to write policy holder particulars to a csv file. Creates ArrayList
* and uses collect joining to add comma for file.
*
* #throws IOException
*/
public void writeToFile() throws IOException {
BufferedWriter writer = new BufferedWriter(
new FileWriter("/Users/johnj/eclipse-workspace/InsuranceProject/insurance.csv", true));
// creates policy holder (insurance) array
ArrayList<String> insurance = new ArrayList<String>();
insurance.add(surname);
insurance.add(Integer.toString(age));
insurance.add(motorType);
insurance.add(motorPolicyId);
// write array to csv file
String collect = insurance.stream().collect(Collectors.joining(", "));
System.out.println(collect);
writer.write(collect);
writer.newLine();
writer.flush();
writer.close();
}
/**
* Builds and generates user input. Will then add it into an array list and
* append to writeToFile(). Included do while loop for user to continue creating
* policy profiles without having to re run program.
*
* #param motorType
*/
public void addPolicyHolder() throws IOException {
try {
do {
// enter policy holder surname. Checks pattern to ensure compliance
System.out.println("Please type your surname...");
surname = scanner.next(pattern).toUpperCase().trim();
setSurname(this.surname);
// user input age
System.out.println("Please type your age...");
age = scanner.nextInt();
setAge(this.age);
// user input motor type which is converted to upper case
System.out.println("Please type your motor type i.e. CAR, TAXI or BUS...");
motorType = scanner.next().toUpperCase().trim();
setMotorType(this.motorType);
System.out.println(); // used to create next line space
// Motor Policy Id should be 3 characters from surname as well as time stamp. If
// time stamp odd number add 1 or else add 0 if even.
motorPolicyId = surname.substring(0, 3) + timeStamp;
if (timeStamp % 2 == 0) {
motorPolicyId = this.motorPolicyId + 0;
} else {
motorPolicyId = this.motorPolicyId + 1;
}
// creates csv file
writeToFile();
// prints completed user input of policy holder
System.out.println();
System.out.println("Surname :" + this.surname);
System.out.println("Age :" + this.age);
System.out.println("Policy Ref :" + this.motorPolicyId);
System.out.println("Motor Type: :" + this.motorType);
System.out.println(); // used to create next line space
// asks user if they would like to create a different policy holder
System.out.println("Add another Policy Holder (Y or N)..");
addAnother = scanner.next();
} while (addAnother.equalsIgnoreCase("Y")); // If N program ends.
} catch (Exception exception) { // if exception program ends
System.out.println(
"There is a problem ... Policy Holder does meet necessary criteria, run the program again.");
} finally {
scanner.close();
System.out.println("Program ended!"); // end of program
}
}
public static void main(String[] args) throws IOException {
InsurancePolicy insurancePolicy = new InsurancePolicy();
insurancePolicy.addPolicyHolder();
}
}
I am able to complete a first run but do while loop fails when trying to add another policy holder.

Is return a better alternative than Sys.out.print in this scenario

This is my tester class for my first programming assignment, which I believe tests the getters and setters correctly, but I was wondering if there is a better method using the return method instead. I'm still quite a novice, as this is my first programming assignment. It feels almost improper to have so many print lines, but is there a better way with return? (At least something not incredibly complex for a java beginner)
/**
A class to test the Assignment class
*/
public class AssignmentTester
{
/**
Main method used to start program
#param args the command line arguments for the program
*/
public static void main(String[] args)
{
System.out.println("TESTING NO-ARGUMENT CONSTRUCTOR AND GETTERS \n=========================================== \n");
Assignment noArgGetterTest = new Assignment();
System.out.println(noArgGetterTest.getTitle() + "\nExpected: Assignment 1 \n");
System.out.println(noArgGetterTest.getDueDate() + "\nExpected: 01/01/2019 \n");
System.out.println(noArgGetterTest.getMaxPoints() + "\nExpected: 10.0 \n");
System.out.println(noArgGetterTest.getCategory() + "\nExpected: Programming Assignments \n \n");
System.out.println("Testing Setters \n=============== \n");
Assignment setterTest = new Assignment();
setterTest.setTitle("CodeLab 1");
System.out.println(setterTest.getTitle() + "\nExpected: CodeLab 1 \n");
setterTest.setDueDate("02/09/2019");
System.out.println(setterTest.getDueDate() + "\nExpected: 02/09/2019 \n");
setterTest.setMaxPoints(5.0);
System.out.println(setterTest.getMaxPoints() + "\nExpected: 5.0 \n");
setterTest.setCategory("CodeLab, Quizzes, ICE");
System.out.println(setterTest.getCategory() + "\nExpected: CodeLab, Quizzes, ICE \n \n");
System.out.println("Testing Argument Constructor and Getters \n======================================== \n");
Assignment getterTest = new Assignment("Quiz 3.1", "03/13/2019", 2.0, "CodeLab, Quizzes, ICE");
System.out.println(getterTest.getTitle() + "\nExpected: Quiz 3.1 \n");
System.out.println(getterTest.getDueDate() + "\nExpected: 03/13/2019 \n");
System.out.println(getterTest.getMaxPoints() + "\nExpected: 2.0 \n");
System.out.println(getterTest.getCategory() + "\nExpected: CodeLab, Quizzes, ICE");
}
}
My first class file that creates the parameters and arguments for creating an assignment:
/**
Describes an assignment's title, due date, total points value, and category
*/
public class Assignment
{
private String title; //Title of assignment
private String dueDate; //Due date of assignment
private double maxPoints; //Max points of assignment
private String category; //Category of assignment
/**
Initialize instance variables for assignment project (no argument-constructor)
*/
public Assignment()
{
title = "Assignment 1";
dueDate = "01/01/2019";
maxPoints = 10.0;
category = "Programming Assignments";
}
/**
Initialize instance variables for the assignment project (argument constructor)
#param t title of assignment
#param d due date of assignment
#param m max points for the assignment
#param c category of assignment
*/
public Assignment(String t, String d, double m,String c)
{
title = t;
dueDate = d;
maxPoints = m;
category = c;
}
/**
Sets the value of title
#param t title of assignment
*/
public void setTitle(String t)
{
title = t;
}
/**
Sets the value of dueDate
#param d due date of assignment
*/
public void setDueDate(String d)
{
dueDate = d;
}
/**
Sets value of maxPoints
#param m max points of assignment
*/
public void setMaxPoints(double m)
{
maxPoints = m;
}
/**
Sets the value of category
#param c category of assignment
*/
public void setCategory(String c)
{
category = c;
}
/**
Returns the value of title
#return title of assingment
*/
public String getTitle()
{
return title;
}
/**
Returns the value of dueDate
#return due date of assignment
*/
public String getDueDate()
{
return dueDate;
}
/**
Returns the value of maxPoints
#return max points of assignment
*/
public double getMaxPoints()
{
return maxPoints;
}
/**
Returns the value of category
#return category of assingmen
*/
public String getCategory()
{
return category;
}
}
// I have done the same problem with using the return keyword, its awesome to use //return.
// but you should know "method" before using return keyword. Basically, you will know //later that the "method" helps you to save writing the same code. Cheers:)
public class AssignmentTester {
public static Assignment noArgumentConstructorAndGetters() {
System.out.println("TESTING NO-ARGUMENT CONSTRUCTOR AND GETTERS \n=========================================== \n");
Assignment noArgGetterTest = new Assignment();
return noArgGetterTest;
}
public static void printMethod(Assignment ass) {
System.out.println(ass.getTitle());
System.out.println(ass.getDueDate());
System.out.println(ass.getMaxPoints());
System.out.println(ass.getCategory());
}
public static Assignment testingSetters() {
System.out.println("Testing Setters \n=============== \n");
Assignment setterTest = new Assignment();
setterTest.setTitle("CodeLab 1");
setterTest.setDueDate("02/09/2019");
setterTest.setMaxPoints(5.0);
setterTest.setCategory("CodeLab, Quizzes, ICE");
return setterTest;
}
public static Assignment testingArgumentsAndConstructors() {
System.out.println("Testing Argument Constructor and Getters \n======================================== \n");
Assignment getterTest = new Assignment("Quiz 3.1", "03/13/2019", 2.0, "CodeLab, Quizzes, ICE");
return getterTest;
}
public static void main(String[] args) {
printMethod(noArgumentConstructorAndGetters());
printMethod(testingSetters());
printMethod(testingArgumentsAndConstructors());
}
}

Java Calculator with classes

OK so i have been working on a calculator with classes(To play with classes but a function) and when ever I run it all i get back is zero no matter what I type in or say to use for the operator. Here is my code:
Main class:
import java.util.Scanner;
//numof = number of numbers in array
// numarrays = the array for user input
// finial = finial number aka the answer
public class Calculator {
public static double finial;
/**
* #return the finial
*/
public static double getFinial() {
return finial;
}
/**
* #param numof the finial to set
*/
public static void setFinial(double finial) {
finial = numof;
}
public static int numof;
/**
* #return the numof
*/
public static int getNumof() {
return numof;
}
/**
* #param numof the numof to set
*/
public static void setNumof(int numof) {
numof = numof;
}
public static double[] numarrays;
/**
* #return the numarrays
*/
public static double[] getNumarrays() {
return numarrays;
}
/**
* #param numarrays the numarrays to set
*/
public static void setNumarrays(double[] numarrays) {
numarrays = numarrays;
}
#SuppressWarnings("resource")
public static void main (String[] args) {
System.out.println("Hello and welcome to my calculator, in this calculator you can add, subtract or multiply");
System.out.println("For the next step I need to know how many numbers you would like to input? ");
int numof;
Scanner numofnums= new Scanner(System.in);
numof = numofnums.nextInt();
Calculator.setNumof(numof);
System.out.println("So next you are going to input the numbers");
double[] numarrays = new double[numof];
for (int k=0; k < numof; k++){
System.out.println("Please enter number");
Scanner input = new Scanner(System.in);
numarrays[k] = input.nextDouble();
}
Calculator.setNumarrays(numarrays);
System.out.println("Please enter what you would like to do with these numbers add,subtract,avg,multiply");
Scanner OP = new Scanner(System.in);
String OPerator= OP.next();
if (OPerator.equals ("add")){
Add.adding();
}
else if (OPerator.equals ("subtract")){
subtract.subtracting();
}
else if (OPerator.equals ("multiply")){
multiply.multiplying();
}
else if (OPerator.equals ("avg")){
avg.avging();
}
System.out.println("The answer is " + Calculator.getFinial());
}
}
here is the add class:
public class Add extends Calculator {
public static void adding() {
double finial = 0;
for (int h = 0; h < Calculator.getNumof(); h++){
finial = finial + Calculator.getNumarrays()[h];
}
Calculator.setFinial(finial);
}
}
I do have three more classes but it is just operator classes let me know if you need them
Just a quick look shows some significant basic issues. For example, in a basic setter, like:
public static void setFinial(double finial) {
finial = numof;
}
from your code, what you most likely intended was
public static void setFinial(double paramFinial) {
finial = paramFinial;
}
If your static variable and your parameter have the same name, you can't access both. The compiler will think you're talking about the parameter. Also, be careful that your setter is using the parameter paramFinial instead of the probably unintentional reference to numof.
It would be a lot easier to read the rest of your code if you would comment what finial, numof, and your other variables represent.

java assignment in string by using charAt()

import java.util.Scanner;
/**
* #(#)wefeqwrf.java
*
* wefeqwrf application
*
* #author
* #version 1.00 2013/11/15
*/
public class wefeqwrf {
public static void main(String[] args) {
// TODO, add your application code
Scanner scan= new Scanner(System.in);
String number = "000";
String a;
int count=0;
for(int i=0;a!="-1";i++)
{
for(int k=0;k<3;k++){
a=scan.next();
a.charAt(0)= number.charAt(k);
if(number.equals("110"))
{
System.out.print("Tebrikler!=110");
count++;
}
else
{
System.out.print("Maalesef olmadı:" + number);
}
}
}
}
}
It gives the error:
error: unexpected type at this code: `a.charAt(0)= number.charAt(k);`
how can I assign the content of a to the specified index of number?
and when I changed the string a to the char a scan.next() does not work why and what can I do is there a any scanner method for char?
You should do it this way:
a = number.charAt(k) + a.substring(1);
You can't assign something to a method. Methods only return something.

Java access protected variable from subclass

I am working on a homework assignment looking at inheritance in java. I am having a little trouble understand how to access an array in the superclass from the subclass. I looked at several other questions, and since I am so new to java, I'm still just not quite getting it.
Here is the super class
import java.text.NumberFormat;
/**
* Bank represents a single Bank containing a number of BankAccounts.
*/
public class Bank {
// Member variables:
/** The array of BankAccount objects contained in this bank. */
protected BankAccount[] myAccounts = new BankAccount[2000];
/** The number of BankAccount objects stored in the array in this bank. */
protected int numberOfAccounts = 0;
// Constructors:
/**
* Creates a Bank.
*/
public Bank() {}
// Methods:
/**
* Creates an account with the name and balance, and adds it to
* the bank's list of accounts.
* If the name already exists, no account will be created.
* #param aName The name for the new account.
* #param aBalance The initial balance for the new account.
*/
public void createAccount( String aName, double aBalance) {
BankAccount existing = this.findAccount( aName);
if( existing != null) return;
BankAccount anAccount = new BankAccount( aBalance, aName);
this.myAccounts[ numberOfAccounts] = anAccount;
this.numberOfAccounts++;
}
/**
* Finds an account in the bank's list of accounts by name.
* If no account is found, this method returns null.
* #param aName The name of the BankAccount to search for.
* #return The BankAccount bearing the given name, if found.
*/
public BankAccount findAccount( String aName) {
BankAccount answer = null;
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
if( aName.equals( anAccount.getName())) {
return( anAccount);
}
}
return( answer);
}
/**
* Returns a String which represents a short summary of
* all the accounts in the bank.
* #return A String representation of all accounts and their balances in the bank.
*/
public String toString() {
String answer = "";
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
String money = currencyFormatter.format( anAccount.getBalance());
answer += anAccount.getName() + " \t" + money + "\n";
}
return( answer);
}
}
and here is the start of the subclass
public class BankSubClass extends Bank{
private double interestPaid;
// Constructor
public BankSubClass(String aName, double aBalance, double aInterest) {
super();
this.interestPaid = aInterest;
}
// Getters
public double getInterestPaid() {return(this.interestPaid);}
// Setters
public void setInterestPaid(double setInterestPaid) {this.interestPaid = setInterestPaid;}
// Other methods
public double endOfYear() {
for (i=0;i<BankAccount.length();i++) {
}
}
}
That for loop at the end are where things are getting a little tripped up. Netbeans is throwing up errors saying "cannot find symbol: variable i". Maybe this has nothing to do with the bank account array I'm trying to use, I don't know. Any help is much appreciated
Thanks for your time!
edit
So here is a continuation of the same homework
Thanks for the replies everyone, your suggestions took care of that problem, I am currently hitting another speed bump at the moment however. The idea behind this method that the for loop is in is to run through the array of BankAccount objects, check to see if any of them are of the InterestAccount type (a class I previously built) and if they are, call the yearlyUpdate() method from that class
Here is the InterestAccount class
public class InterestAccount extends BankAccount {
private double interestRate;
// Constructor
/**
* Create and interest bearing bank account with a balance, name,
* and interest rate
* #param aBalance The balance of the account
* #param aName The name tied to the account
* #param myInterestRate The interest rate of the account
*/
public InterestAccount(double aBalance, String aName, double myInterestRate) {
super(aBalance, aName);
this.interestRate = myInterestRate;
}
// Getters
/**
* Gets the interest rate of the account
* #return the interest rate of the account
*/
public double getInterestRate() {return(this.interestRate);}
// Setters
/**
* Sets the interest rate of the account
* #param interestSet The new interest rate of the account
*/
public void setInterestRate(int interestSet) {this.interestRate = interestSet;}
// Other Methods
/**
* Calculates the interest earned on the account over a year
* #return the interest earned over a year
*/
public double yearlyUpdate() {
double answer = (super.getBalance()*this.interestRate);
return answer;
}
}
Here is the super class I am currently working with
import java.text.NumberFormat;
/**
* Bank represents a single Bank containing a number of BankAccounts.
*/
public class Bank {
// Member variables:
/** The array of BankAccount objects contained in this bank. */
protected BankAccount[] myAccounts = new BankAccount[2000];
/** The number of BankAccount objects stored in the array in this bank. */
protected int numberOfAccounts = 0;
// Constructors:
/**
* Creates a Bank.
*/
public Bank() {}
// Methods:
/**
* Creates an account with the name and balance, and adds it to
* the bank's list of accounts.
* If the name already exists, no account will be created.
* #param aName The name for the new account.
* #param aBalance The initial balance for the new account.
*/
public void createAccount( String aName, double aBalance) {
BankAccount existing = this.findAccount( aName);
if( existing != null) return;
BankAccount anAccount = new BankAccount( aBalance, aName);
this.myAccounts[ numberOfAccounts] = anAccount;
this.numberOfAccounts++;
}
/**
* Finds an account in the bank's list of accounts by name.
* If no account is found, this method returns null.
* #param aName The name of the BankAccount to search for.
* #return The BankAccount bearing the given name, if found.
*/
public BankAccount findAccount( String aName) {
BankAccount answer = null;
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
if( aName.equals( anAccount.getName())) {
return( anAccount);
}
}
return( answer);
}
/**
* Returns a String which represents a short summary of
* all the accounts in the bank.
* #return A String representation of all accounts and their balances in the bank.
*/
public String toString() {
String answer = "";
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
for( int index = 0; index < numberOfAccounts; index++) {
BankAccount anAccount = this.myAccounts[ index];
String money = currencyFormatter.format( anAccount.getBalance());
answer += anAccount.getName() + " \t" + money + "\n";
}
return( answer);
}
}
And finally, here is the subclass in which I am trying to run this for loop
public class BankSubClass extends Bank{
private double interestPaid;
// Constructor
public BankSubClass(String aName, double aBalance, double aInterest) {
super();
this.interestPaid = aInterest;
}
// Getters
public double getInterestPaid() {return(this.interestPaid);}
// Setters
public void setInterestPaid(double setInterestPaid) {this.interestPaid = setInterestPaid;}
// Other methods
public double endOfYear() {
double trackInterest=0;
for (int i=0;i<numberOfAccounts;i++) {
BankAccount working = myAccounts[i];
boolean hasInterest = working instanceof InterestAccount;
if (hasInterest) {
trackInterest = trackInterest + working.yearlyUpdate();
}
return trackInterest;
}
}
}
currently netbeans can't find the "yearlyUpdate()" method when attempting to call it on "working" what I'm not understanding is since the previous code verified that the working object was of the InterestAccount type, it should have that method available
Thanks for the help!
// Other methods
public double endOfYear() {
for (i=0;i<BankAccount.length();i++) {
}
}
You need to declare i
// Other methods
public double endOfYear() {
for (int i=0;i<BankAccount.length();i++) {
}
}
In your loop, variable i is undeclared. Also, since I think you wish to loop through the accounts in the array, I think you should be using the following:
for(int i = 0; < numberOfAccounts; i++)
{
BankAccount bankAccount = myAccounts[i];
// other stuff
}
Like the error says: i is undefined.
try:
for (int i=0;i<BankAccount.length();i++)
I'm guessing that is still bad since you want the length of the array, not the BankAccount class (which may be undefined)
for (int i=0;i<myAccounts.length();i++)
For the error, you need to define the variable i before using it in BankSubClass.endOfYear. The statement should be
for (int i=0;i<BankAccount.length();i++)
You didn't declare i in side the for loop
for (int i=0;i<BankAccount.length();i++)

Categories

Resources