gpt4 book ai didi

java - 来自不同类的静态变量的问题

转载 作者:行者123 更新时间:2023-12-01 16:35:58 25 4
gpt4 key购买 nike

我仍在开发那个文本冒险游戏,我需要有关静态变量的帮助。我在 repl.it 中有第二个文件,名为 Safe.java,它包含我的谜题的基本代码。问题是非静态方法 toString 和 findSum 无法从静态上下文中引用。

问题#1:toString

if(gotPaper == true)
{
System.out.println("The paper has 4 numbers. The numbers in order is: " + Safe.toString());
}

问题 #2 和 #3:findSum

  public static int keypad()
{
Scanner key = new Scanner(System.in);

if(keypadOpen == true)
{
System.out.println("The keypad calmy tells you, \"Thank you for entering the correct number. I have nothing more for you.\"");
}
else
{
int humanSum;
System.out.print("The keypad yells at you, \"Enter the sum of all 4 numbers!\"");
humanSum = key.nextInt();
if(humanSum == Safe.findSum())
{
keypadOpen = true;
System.out.println("The keypad calmy tells you, \"Thank you for entering the correct number.\" One of the door's locks are undone.");
}
else if(humanSum != Safe.findSum())
{
System.out.println("The keypad yells at you, \"ERROR: Entered value is incorrect!\"");
System.out.print("You sulk to the door, defeated.");
x++;
}

Safe.java 中的 findSum 和 toString

    public int findSum() 
{
int sum = 0;
for(int i = 0; i < code.length; i++)
{
sum += code[i];
}
return sum;
}


public String toString()
{
String written;
written = "[";
for (int i = 0; i < code.length - 1; i++)
{
written = written + (code[i]+", ");
}
written = written + (code[code.length - 1]+"]");
return written;
}

最佳答案

您可以从Safe创建静态对象

static Safe safeObj = new Safe();

,并从对象中使用findSumtoString()

safeObj.findSum();

关于java - 来自不同类的静态变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61946335/

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