如何在类中使用方法内计算的变量值?
我对编程很陌生,不太了解。我一直在试图建立一个简单的游戏,用户和计算机通过滚动骰子来争夺积分。我的方法发布如下。电脑只允许每回合获得20点。如何在类中使用方法内计算的变量值?
我的问题是,我需要在方法被调用和完成后记住变量computerTotal的值。我想确保每当computerTurn方法完成后,我可以在该方法之外使用计算的变量computerTotal。我试图在.java文件类(但方法的外部)中建立一个新的int,然后在该方法内使用该int来保存该值,但是我收到有关整数需要静态的错误?
这对我来说都非常困惑。谁能帮我吗?
公共静态无效computerTurn() {
System.out.println("Passed to Computer.");
Die computerDie1, computerDie2;
int computerRound, computerTotal;
computerRound = 0;
computerTotal = 0;
while (computerTotal < 21){
computerDie1 = new Die();
computerDie2 = new Die();
computerDie1.roll();
computerDie2.roll();
System.out.println("\n" + "CPU Die One: " + computerDie1 + ", CPU Die Two: " + computerDie2 + "\n");
computerRound = computerDie1.getFaceValue() + computerDie2.getFaceValue();
int cpuDie1Value;
int cpuDie2Value;
cpuDie1Value = computerDie1.getFaceValue();
cpuDie2Value = computerDie2.getFaceValue();
System.out.println ("Points rolled this round for the Computer: " + computerRound);
computerTotal = computerTotal + computerRound;
System.out.println ("Total points for the Computer: " + computerTotal + "\n");
}
任何一个方法中创建的变量是“局部变量”,意味着它们不能该方法之外使用。把一个静态变量放在一个方法之外来创建可以在任何地方使用的“全局变量”。
的方法添加到您的类
public static int getComputerTotal() { return ComputerTotal;}
然后你就可以获取类之外的值通过执行类似:
ComputerTurn();
ComputerTurn.getComputerTotal();
把变量外的方法是正确的跟踪,但由于此方法是static
(意思是它不能访问依赖于对象实例的变量),它只能访问静态变量。在类中声明computerTotal
的方法外,使用以下:
private static int computerTotal;
你或许应该做一些研究,在面向对象编程和Java中的意思static
。
将computerTotal声明为您类的成员变量,以使其值甚至在函数外部可用。
class MyClass{
private int computerTotal ;
public void function myFunction()
{
........
......... // your calculations
computerTotal = computerTotal + computerRound;
}
public int getComputerTotal(){return computerTotal ;}
}
您必须声明任何方法外computertotal来留住他们。所以像这样:
public class name {
int computertotal = 0; //v=can just uuse int computertotal;
public void method() {
while(computertotal < 20) {
computertotal += 1;
}
}
}
现在他变量被保存!
您可能需要添加一些setters和getters来从另一个类中获取int。
class NewClass {
private int yourInt = 1;
}
它告诉你使它成为一个静态变量,因为你可以在一份声明中像
NewClass.yourInt;
来调用它,一个静态变量是指与一个类关联,而不是那个对象类。
安装程序和获取程序是允许您从其他类中检索或设置私有值的方法。您可能想要将它们添加到声明int的NewClass中。安装者和获得者看起来像这样。
二传手:
public void setYourInt(int newInt) {
this.yourInt = newInt;
}
消气:
public int getYourInt() {
return this.yourInt;
}