如何在Java中通过多个类保存一个值?

How do I save a value through multiple classes in Java?

我是 java 的新手,一般来说是编码方面的新手。我试图创建一个游戏作为一个小的副项目,以便在等待我的 comp sci classes 中的下一个任务时乱七八糟。我 运行 遇到了一个问题,当我在开始时调用我的 classes 时,在调用下一个时忘记了这些值。例如,当我说我要“去写字楼”打工,给自己挣点钱,我马上“去银行”时现金就没了。我怎样才能让游戏记住我工作时有多少现金?我试图全神贯注于序列化,但它非常令人困惑。我想知道是否有更好的方法来做到这一点,或者是否有人可以向我解释如何去做。非常感谢任何回复的人!

import java.util.Scanner;
public class Game {
   public static void main(String[] args) {

    Work work = new Work();
    Bank bank = new Bank();
    Scanner input = new Scanner(System.in);
    int process = 0;
    while (process == 0) {
        System.out.println("What would you like to do?");
        System.out.println("1) Go to the Bank");
        System.out.println("2) Go to Office Building");
        System.out.println("3) Exit Game");
        int response = input.nextInt();
        if (response == 1) {
            Bank.main(args);
        }
        if (response == 2) {
            Work.main(args);
        }
        if (response == 3) {
            process++;
        }
    }
}

}

上面的代码是我调用其他 classes 的地方。 这是我的另外两个主要 classes 和它们各自的 classes.

import java.util.Scanner;
public class Work extends Working {
public static void main(String [] args) {
    Working work = new Working();
    Bank bank = new Bank();
    Scanner input = new Scanner(System.in);
    int process = 0;
    int jobExperience = 0;

    while (jobExperience == 0 && process == 0) {
        System.out.println("Welcome! Would you like to apply for a job? Y/N:");
        String response = input.next();

        if (response.equalsIgnoreCase("Y")) {
            jobExperience++;
        }
        else {
            System.out.println("Alright, see you next time!");
            process++;
        }
    }

    while (process == 0) {
        System.out.println("Welcome! Would you like to work? Y/N:");
        String response = input.next();

        if (response.equalsIgnoreCase("Y")) {
            System.out.println("How many hours would you like to work? 1-8:");
            int hours = input.nextInt();

            if (hours >= 1 && hours <= 8) {
                work.setHours(hours);
                work.setJob(jobExperience);
                work.wageCalc();
                work.setPaycheck();
                bank.setCash(bank.getCash()+work.getPaycheck());
                work.printStatement();
                jobExperience++;
                process++;
            }
        }
        else {
            System.out.println("Alright, see you next time!");
            process++;
        }
    }
}

}

class 作业的第 2 部分:

public class Working {
double wage;
double hours;
double paycheck;
int job;

public double getHours() {
    return hours;
}

public void setHours(double hours) {
    this.hours = hours;
}

public double getWage() {
    return wage;
}

public void setWage(double wage) {
    this.wage = wage;
}

public int getJob() {
    return job;
}

public void setJob(int job) {
    this.job = job;
}

public void wageCalc() {
    if (getJob() == 1) {
        setWage(15);
    }
    if (getJob() == 2) {
        setWage(20);
    }
    if (getJob() == 3) {
        setWage(30);
    }
    if (getJob() == 4) {
        setWage(45);
    }
    if (getJob() == 5) {
        setWage(70);
    }
    if (getJob() >= 6) {
        setWage(100);
    }
}

public void setPaycheck() {
    paycheck = hours * wage;
}

public double getPaycheck() {
    return paycheck;
}

public void printStatement() {
    System.out.println("You worked " + getHours() + " hours at a pay rate of $" + getWage() + "/hr and earned $" + getPaycheck() + ".");
}

}

我希望 Bank 和 Work classes 记住彼此的价值观。

import java.util.Scanner;
public class Bank extends Banking {
public static void main(String[] args) {
    Banking bank = new Banking();
    Scanner input = new Scanner(System.in);
    int process = 0;

    System.out.println("Thank you for banking with us. How can we help you?");
    while (process == 0) {
        System.out.println();

        System.out.println("Press 'B' to check your balance.  Press 'D' to deposit money. Press 'W' to withdraw money. Press 'E' to exit.");
        String response = input.next();

        if (response.equalsIgnoreCase("B")) {
            System.out.println("Your bank balance is currently $" + bank.getBalance());
            System.out.println("You currently have $" + bank.getCash() + " in cash.");
        }

        if (response.equalsIgnoreCase("D")) {
            System.out.println("How much would you like to deposit?");
            double amount = input.nextDouble();
            if (bank.getCash() >= amount) {
                bank.setDeposit(amount);
                bank.Deposit();
                bank.setCash(bank.getCash() - amount);
                System.out.println("You have deposited $" + bank.getDeposit() + ".");
                System.out.println("Your new balance is $" + bank.getBalance());
            }
            else {
                System.out.println("Sorry, you do not have enough cash to deposit.");
            }
        }

        if (response.equalsIgnoreCase("W") && bank.getBalance() > 0) {
            System.out.println("How much would you like to withdraw?");
            double amount = input.nextDouble();

            if (amount < bank.getBalance()) {
                bank.setWithdraw(amount);
                bank.Withdraw();
                System.out.println("You have withdrawn $" + bank.getWithdraw() + ".");
                System.out.println("Your new balance is $" + bank.getBalance());
            }

            else {
                System.out.println("You do not have sufficient funds to withdraw");
                System.out.println("Your current balance is $" + bank.getBalance());
            }
        }

        else if (response.equalsIgnoreCase("W") && bank.getBalance() <= 0) {
            System.out.println("You do not have sufficient funds to withdraw");
        }

        if (response.equalsIgnoreCase("E")) {
            process = 2;
            System.out.println("Goodbye!");
        }
    }
}

}

这是我银行的第二部分:

public class Banking {
private double balance;
private double withdraw;
private double deposit;
private double cash;

public void setCash(double cash) {
    this.cash = cash;
}

public double getCash() {
    return cash;
}

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

public double getBalance() {
    return balance;
}

public void setWithdraw(double withdraw) {
    this.withdraw = withdraw;
}

public double getWithdraw() {
    return withdraw;
}

public void setDeposit(double deposit) {
    this.deposit = deposit;
}

public double getDeposit() {
    return deposit;
}

public void Withdraw() {
    balance = balance - withdraw;
}
public void Deposit() {
    balance = balance + deposit;
}

}

简短的回答是,您需要在 类 之间传递某种“状态”,而它们(可选,取决于它们所做的)需要传回新的“状态”

如何做到这一点取决于您要解决的问题,但您应该首先查看 Passing Information to a Method or a Constructor and Returning a Value from a Method 作为起点。

例如,我将做一些您可能不喜欢的事情,但它会演示基本概念。

首先是“契约”。我们需要一些方法来“包含”我们想要跟踪的各种事物并定义它们愿意执行的操作,为此,我们从一些基本的 interfaces

开始
public interface Life {
    public int getExperience();
    public void addExperience(int experience);
}

public interface Job {
    public double getHours();
    public double getHourlyRate();
    public PayCheck getPayCheck();
}

public interface PayCheck {
    public int getExperienceGained();
    public double getAmount();
    public String getSummary();
}

public interface Bank {
    public double getBalance();
    public void deposit(PayCheck payCheck);
    public void deposit(double amount);
    public double withdraw(double amount);
    public String getSummary();
}

nb:你不知道我多么想要一个可变的和不可变的Life因为不是每个人都应该能够增加经验

接下来,我们需要一些实际的实现(通常我会创建 abstract 定义大部分常见工作的版本,但这是一个基本示例,所以我跳过了这些)

public class DefaultLife implements Life {
    private int experience;

    @Override
    public int getExperience() {
        return experience;
    }

    @Override
    public void addExperience(int experience) {
        this.experience += experience;
    }
    
}

public class DefaultJob implements Job {

    private double hoursWorked;
    private double hourlyRate;

    public DefaultJob(Life life, double hoursWorked) {
        this.hoursWorked = hoursWorked;
        int experience = life.getExperience();

        if (experience <= 1) {
            hourlyRate = 15;
        } else if (experience == 2) {
            hourlyRate = 20;
        } else if (experience == 3) {
            hourlyRate = 30;
        } else if (experience == 4) {
            hourlyRate = 45;
        } else if (experience == 5) {
            hourlyRate = 70;
        } else {
            hourlyRate = 100;
        }
    }

    @Override
    public double getHours() {
        return hoursWorked;
    }

    @Override
    public double getHourlyRate() {
        return hourlyRate;
    }

    @Override
    public PayCheck getPayCheck() {
        double amount = getHours() * getHourlyRate();
        return new DefaultPayCheck(1, this);
    }
}

public class DefaultPayCheck implements PayCheck {

    private int experienceGained;
    private double amount;
    private Job job;

    public DefaultPayCheck(int experience, Job job) {
        this.experienceGained = experience;
        this.amount = job.getHourlyRate() * job.getHours();
        this.job = job;
    }

    @Override
    public int getExperienceGained() {
        return experienceGained;
    }

    @Override
    public double getAmount() {
        return amount;
    }

    public Job getJob() {
        return job;
    }

    @Override
    public String getSummary() {
        Job job = getJob();
        return "You worked " + job.getHours() + " hours @ $" + job.getHourlyRate() + " and earned $" + getAmount() + " and have earned and additional " + getExperienceGained() + " experience";
    }
}

public class DefaultBank implements Bank {
    
    private double balance;

    @Override
    public double getBalance() {
        return balance;
    }

    @Override
    public void deposit(PayCheck payCheck) {
        deposit(payCheck.getAmount());
    }

    @Override
    public void deposit(double amount) {
        balance += amount;
    }

    @Override
    public double withdraw(double amount) {
        // All your momey belong to us
        return 0;
    }

    @Override
    public String getSummary() {
        return "You have $" + balance + " in the bank";
    }
    
}

但是为什么?!好吧,看看DefaultJob。它引用了 Life 的实例。它不关心 Life 是如何实现的,只关心你传递给它的内容是否符合 interface 所描述的联系……这是非常强大的东西。

现在,如果这只是让您感到困惑的话 ‍。您可以删除所有 interface 并简单地使用“默认”类,但您正在失去很多潜在机会(我的意思是,您可以考虑多少工作?有多少家银行?)

最后,我们需要一些东西来完成它...

Scanner scanner = new Scanner(System.in);

Life life = new DefaultLife();
Bank bank = new DefaultBank();

boolean done = false;
do {
    if (life.getExperience() == 0) {
        System.out.println("Welcome! Would you like to apply for a job? Y/N:");
        String response = scanner.nextLine();

        if ("Y".equalsIgnoreCase(response)) {
            life.addExperience(1);
        } else {
            System.out.println("Alright, see you next time!");
            done = true;
        }
    }

    if (!done) {
        System.out.println("Welcome to work!");
        boolean isValid = false;
        while (!isValid) {
            System.out.println("How many hours would you like to work? 1-8:");
            String input = scanner.nextLine();
            try {
                int hours = Integer.parseInt(input);
                if (hours < 1) {
                    System.out.println("Okay, see you next time!");
                    isValid = true;
                } else if (hours > 0 && hours < 9) {
                    isValid = true;
                    Job job = new DefaultJob(life, hours);
                    PayCheck payCheck = job.getPayCheck();
                    System.out.println(payCheck.getSummary());

                    life.addExperience(payCheck.getExperienceGained());
                    double amount = payCheck.getAmount();
                    bank.deposit(payCheck);
                    System.out.println(bank.getSummary());
                } else {
                    System.out.println(hours + " is not a valid number of hours!");
                }
            } catch (NumberFormatException exp) {
                System.out.println(input + " is not a valid value!");
            }
        }
    }
    System.out.println("Would you like to continue? [Y]");
    done = !"Y".equalsIgnoreCase(scanner.nextLine());
} while (!done);

现在,这不是您可以执行此操作的唯一方法(您可以让 Job 更新 Life 本身的 experience,但这是一个架构决定)

可运行示例

而且因为尝试将单独的代码片段粘贴在一起总是很有趣

import java.util.Scanner;

public class GameOfLife {

    public static void main(String[] args) {
        new GameOfLife();
    }

    public GameOfLife() {
        Scanner scanner = new Scanner(System.in);

        Life life = new DefaultLife();
        Bank bank = new DefaultBank();

        boolean done = false;
        do {
            if (life.getExperience() == 0) {
                System.out.println("Welcome! Would you like to apply for a job? Y/N:");
                String response = scanner.nextLine();

                if ("Y".equalsIgnoreCase(response)) {
                    life.addExperience(1);
                } else {
                    System.out.println("Alright, see you next time!");
                    done = true;
                }
            }

            if (!done) {
                System.out.println("Welcome to work!");
                boolean isValid = false;
                while (!isValid) {
                    System.out.println("How many hours would you like to work? 1-8:");
                    String input = scanner.nextLine();
                    try {
                        int hours = Integer.parseInt(input);
                        if (hours < 1) {
                            System.out.println("Okay, see you next time!");
                            isValid = true;
                        } else if (hours > 0 && hours < 9) {
                            isValid = true;
                            Job job = new DefaultJob(life, hours);
                            PayCheck payCheck = job.getPayCheck();
                            System.out.println(payCheck.getSummary());

                            life.addExperience(payCheck.getExperienceGained());
                            double amount = payCheck.getAmount();
                            bank.deposit(payCheck);
                            System.out.println(bank.getSummary());
                        } else {
                            System.out.println(hours + " is not a valid number of hours!");
                        }
                    } catch (NumberFormatException exp) {
                        System.out.println(input + " is not a valid value!");
                    }
                }
            }
            System.out.println("Would you like to continue? [Y]");
            done = !"Y".equalsIgnoreCase(scanner.nextLine());
        } while (!done);
    }

    public interface Life {

        public int getExperience();

        public void addExperience(int experience);
    }

    public interface Job {

        public double getHours();

        public double getHourlyRate();

        public PayCheck getPayCheck();
    }

    public interface PayCheck {

        public int getExperienceGained();

        public double getAmount();

        public String getSummary();
    }

    public interface Bank {

        public double getBalance();

        public void deposit(PayCheck payCheck);

        public void deposit(double amount);

        public double withdraw(double amount);

        public String getSummary();
    }

    public class DefaultLife implements Life {

        private int experience;

        @Override
        public int getExperience() {
            return experience;
        }

        @Override
        public void addExperience(int experience) {
            this.experience += experience;
        }

    }

    public class DefaultJob implements Job {

        private double hoursWorked;
        private double hourlyRate;

        public DefaultJob(Life life, double hoursWorked) {
            this.hoursWorked = hoursWorked;
            int experience = life.getExperience();

            if (experience <= 1) {
                hourlyRate = 15;
            } else if (experience == 2) {
                hourlyRate = 20;
            } else if (experience == 3) {
                hourlyRate = 30;
            } else if (experience == 4) {
                hourlyRate = 45;
            } else if (experience == 5) {
                hourlyRate = 70;
            } else {
                hourlyRate = 100;
            }
        }

        @Override
        public double getHours() {
            return hoursWorked;
        }

        @Override
        public double getHourlyRate() {
            return hourlyRate;
        }

        @Override
        public PayCheck getPayCheck() {
            double amount = getHours() * getHourlyRate();
            return new DefaultPayCheck(1, this);
        }
    }

    public class DefaultPayCheck implements PayCheck {

        private int experienceGained;
        private double amount;
        private Job job;

        public DefaultPayCheck(int experience, Job job) {
            this.experienceGained = experience;
            this.amount = job.getHourlyRate() * job.getHours();
            this.job = job;
        }

        @Override
        public int getExperienceGained() {
            return experienceGained;
        }

        @Override
        public double getAmount() {
            return amount;
        }

        public Job getJob() {
            return job;
        }

        @Override
        public String getSummary() {
            Job job = getJob();
            return "You worked " + job.getHours() + " hours @ $" + job.getHourlyRate() + " and earned $" + getAmount() + " and have earned and additional " + getExperienceGained() + " experience";
        }
    }

    public class DefaultBank implements Bank {

        private double balance;

        @Override
        public double getBalance() {
            return balance;
        }

        @Override
        public void deposit(PayCheck payCheck) {
            deposit(payCheck.getAmount());
        }

        @Override
        public void deposit(double amount) {
            balance += amount;
        }

        @Override
        public double withdraw(double amount) {
            // All your momey belong to us
            return 0;
        }

        @Override
        public String getSummary() {
            return "You have $" + balance + " in the bank";
        }

    }
}