Ahmed Abdullah
Ahmed Abdullah

Reputation: 19

how to increment an instance variable from a different class?

I first set a class for the student's balance depending on how many courses they want to enroll in (more details will be added later). my issue is that I cannot find a way to increment the balance variable in the main class?

public class StudentBalance {

    private int balance;


    public StudentBalance() {
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

 }
public class newTest {

static ArrayList<String> courses = new ArrayList<>();
private static StudentBalance newBalance = new StudentBalance();
private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    boolean start = true;

    while (start) {

        System.out.println("1 for subjects and 2 to print");
        int choice = scanner.nextInt();
        switch (choice) {
            case 1:
                courseChoice();
                break;
            case 2:
                printStudentsSubject();
                break;
            default:
                start = false;

        }


    }
}

static void printStudentsSubject() {
    System.out.println("Enrolled students subject list: ");
    for (int i = 0; i < courses.size(); i++) {
        System.out.println((i + 1) + ": " + courses.get(i) +
                "\nBalance: " + newBalance.getBalance()
                + "\n #################################");


    }
}

I'm trying to find a way to add 9000 each time a course is added to the instance variable Balance. than i want to print it but I cant do the first part.

private static void courseChoice() {

    int price = 9000;
    System.out.println("ENTER SUBJECT: \n");
    String studentsCourses = scanner.next();
    courses.add(studentsCourses);
    if (courses.size() > 0) {
        newBalance.setBalance(price);
    }


}

}

Upvotes: 0

Views: 109

Answers (1)

Luck_LATL
Luck_LATL

Reputation: 89

Why do you use a class for StudentBalance? You could simply define an integer (int) and add the amount you want to it.

Like this.

studentBalance += price;

Else you would make a addCourse-Method.

private void addCourse(string name, int price)
{
    courses.add(name);
    newBalance.setBalance(newBalance.getBalance + price)
}

This method would you call everytime you add a new course. Then you define the name and the price with the parameters.

Upvotes: 2

Related Questions