2016-09-18 130 views
0

所以,在我的java类的开始,我定义了全局: static long world;。 然后我有几个函数使用world作为参数。其中一个名为setCell的函数无法按预期工作,我无法弄清楚原因。我曾尝试误差的println命令搜索,所以现在我的代码看起来是这样的:方法不全局更新变量?

public static long setCell(long world, int col, int row, boolean newval){ 
    if(col>= 0 && col<8 && row>=0 && row<8){ 
     int bitPosition = col + 8*row; 
     long newWorld = PackedLong.set(world, bitPosition, newval); 
     System.out.println(newWorld); 
     world = newWorld; 
     System.out.println(world); 
     return world; 
    } 
    else{ 
     return world; 
    } 
} 

代码的主要思想是,它应该通过改变其位中的一个与PackedLong.set方法更新world(这是运行良好),然后返回新更新的world

如果我们现在运行:

world =0x20A0600000000000L; 
System.out.println(world); 
setCell(world, 1, 1, true); 
System.out.println(world); 
的主要方法

,我们得到以下的输出:

2350984558603665408 2350984558603665920 2350984558603665920 2350984558603665408

由此我得出的结论是命令里面的setCell方法的工作原理打算,但该方法不会在整个代码中“全局”地更改world。我该如何解决这个问题? 非常感谢! :)

回答

3

你有参数world

public static long setCell(long world, int col, int row, boolean newval) 

这将隐藏的全局变量,而是更新参数。您应该避免将名称隐藏在同一范围内的其他变量。相反,请为参数选择不同的名称。

+0

这是正确的,但是如何解决问题? –

+1

使用不隐藏全局变量的参数名称。 – Kelvin

+0

@凯文谢谢你的回答!你能不能更具体一点我应该改变我的变量?我在开始时尝试写'static long initialWorld',在main方法的每个地方都把'world'改成'initialWorld',并且不改变'setCell'中的任何东西,但错误仍然存​​在。 – Jhonny

2

首先,使用全局变量是不好的,因为它们是一个隐藏依赖项。目前还不清楚一个班级是否使用world,除非你真的去找它并在代码中使用它。这样的代码很难调试。

long没有这个方法来设置它,而不是将它传递给一些静态函数,并且它更新了一些全局变量(a la C),你最好将它封装在提供的类中此功能:

class World { 
    private long world; 

    public World(long value) { 
     this.world = value; 
    } 

    public void setCell(int col, int row, boolean newval) { 
     if(col>= 0 && col<8 && row>=0 && row<8){ 
      int bitPosition = col + 8*row; 
      world = PackedLong.set(world, bitPosition, newval); 
     } 
    } 

    @Override 
    public String toString() { 
     return String.valueOf(world); // Or print a hexadecimal presentation. 
    } 
} 

类,可以让普通的数据(如long智能。它也允许你删除一个参数(因为它保存在内部)。

它也将更加清晰,你改变world

World world = new World(0x20A0600000000000L); 
System.out.println(world); 
world.setCell(1, 1, true); // Aha, 'world' is being altered 
System.out.println(world); 

开了为什么代码不起作用正确的答案。

0

我相信@Jorn Vernee的回答是最好的。 https://stackoverflow.com/a/39561744/4506528

但是,我会用极其糟糕的编码练习来回答你的问题,演示如何使用语言功能实现此目的。如果你的班级做得好,你应该永远不要必须这样做。

如果你的类被称为Story和静态字段名为world,您可以直接从地方使用Story.world引用它。这包括重新分配它。

public class Story { 
    public static String world = "Saturn"; 

    public static void main(String[] args) { 
     doStuff("Earth"); 
     System.out.println(world); 
    } 

    public static void doStuff(String world) { 
     Story.world = "Europa"; 
     world = "Mars"; 
    } 
} 

即使这提供了一个回答你的问题,我不鼓励使用静态字段这样。请不要把这个答案付诸实践。


  • long是指在一个非常具体的行为方式:它的行为应该被封装到一个类。

  • 请勿使用静态字段来描述系统的状态。

  • 更改方法的参数名称以避免读取代码时出现混淆。