【问题标题】:Problems with Static Variables from Different a Class来自不同类的静态变量的问题
【发布时间】:2020-05-22 01:17:53
【问题描述】:

我仍在开发那个文字冒险游戏,我需要静态变量方面的帮助。我在 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;
}

【问题讨论】:

    标签: java string class


    【解决方案1】:

    你可以从Safe创建一个静态对象

    static Safe safeObj = new Safe();
    

    ,并使用对象中的findSumtoString()

    safeObj.findSum();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多