gpt4 book ai didi

java - 声明的数组给我 "Exception in thread "main"java.lang.NullPointerException"错误

转载 作者:行者123 更新时间:2023-11-30 03:49:07 27 4
gpt4 key购买 nike

线程“main”中出现异常 java.lang.NullPointerException 在 Game.main(Game.java:12)

我尝试过搜索,这显然意味着我试图在“机器[0].setPayoutRate(35);”

当我尝试调试程序时,对象数组不会显示为三个对象。只是一个值为“SlotMachine[3]”的值,这对我来说没有多大意义。有什么想法吗?

import java.util.Scanner;

public class Game {
public static void main(String[] args) {

Scanner userInput = new Scanner(System.in);
SlotMachine[] machines;
machines = new SlotMachine[3];

int cash = 0, totalPlays = 0;

machines[0].setPayoutRate(35);
machines[1].setPayoutRate(100);
machines[2].setPayoutRate(10);

machines[0].setPayoutAmount(30);
machines[1].setPayoutAmount(60);
machines[2].setPayoutAmount(11);

System.out.println("How many quarters do you have?");
cash = userInput.nextInt();

System.out.println("how many times has the first machine been played?");
machines[0].settimesPlayed(userInput.nextInt());

System.out
.println("how many times has the second machine been played?");
machines[1].settimesPlayed(userInput.nextInt());

System.out.println("how many times has the third machine been played?");
machines[2].settimesPlayed(userInput.nextInt());

while (cash >= 1) {
if (cash >= 1) {
cash = machines[0].play();
totalPlays++;
}
if (cash >= 1) {
cash = machines[0].play();
totalPlays++;
}
if (cash >= 1) {
cash = machines[0].play();
totalPlays++;
}
}
System.out.println("You played: " + totalPlays + " times.");
}
}

主类在上面^对象类如下

public class SlotMachine {

private int timesPlayed;
private int payoutRate;
private int payoutAmount;

public SlotMachine(int timesPlayed, int payoutRate, int payoutAmount) {
this.timesPlayed = timesPlayed;
this.payoutRate = payoutRate;
this.payoutAmount = payoutAmount;
}

public int getTimesPlayed() {
return this.timesPlayed;
}

public void settimesPlayed(int timesPlayed) {
this.timesPlayed = timesPlayed;
}

public int getPayoutRate() {
return this.payoutRate;
}

public void setPayoutRate(int payoutRate) {
this.payoutRate = payoutRate;
}

public int getPayoutAmount() {
return this.payoutAmount;
}

public void setPayoutAmount(int payoutAmount) {
this.payoutAmount = payoutAmount;
}

public int play() {
int moneyExchange = 0;
timesPlayed++;

if (timesPlayed != payoutRate) {
moneyExchange = -1;
} else if (timesPlayed == payoutRate) {
moneyExchange = payoutAmount;
timesPlayed = 0;
}

return moneyExchange;
}

}

最佳答案

您声明了长度为 3 的数组,但未为其分配任何新的 SlotMachine,因此所有元素仍为 null,导致 NullPointerException。初始化您的数组元素。

machines = new SlotMachine[3];
machines[0] = new SlotMachine(0, 35, 30);
machines[1] = new SlotMachine(0, 100, 60);
machines[2] = new SlotMachine(0, 10, 11);

然后你可以通过数组访问它们。

关于java - 声明的数组给我 "Exception in thread "main"java.lang.NullPointerException"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com