我正在尝试创建一个 JSON 文件来写入区块链数据。我正在引用声明的 getter 方法,以便将信息传递给 JSONObject,但它给我的错误是我无法在静态上下文中传递非静态方法,但没有任何内容被声明为静态。
**METHOD GIVING THE ERROR (FOR EACH .PUT LINE)**
`public void toJsonFile()
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", Block.getData());
jsonObject.put("timestamp", Block.getTimeStamp());
jsonObject.put("previousHash", Block.getPrevHash());
jsonObject.put("currentHash", Block.getHash());
try (FileWriter file = new FileWriter("blockchain.json")) {
file.write(jsonObject.toString());
file.flush();
file.close();
}
catch (IOException e) {
e.printStackTrace();
}
}`
**BLOCK STRUCTURE**
`package blockchainproject_v1;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
public class Block
{
private String hash;
private String prevHash;
private String data;
private long timeStamp;
private int index;
private int nonce;
public Block(String prevHash, String data, long timeStamp, int index) {
this.prevHash = prevHash;
this.data = data;
this.timeStamp = timeStamp;
this.index = index;
this.nonce = 0;
this.hash = Block.calculateHash(this);
}
public String getHash() {
return hash;
}
public String getPrevHash() {
return prevHash;
}
public String getData() {
return data;
}
public long getTimeStamp() {
return timeStamp;
}
public int getIndex() {
return index;
}`
我尝试将变量和方法切换为静态,这导致错误消失,但每个块的数据相同,并且未创建文件。我也手动创建了文件,但没有写入任何内容。
我尝试在使用前将返回值分配给不同的变量,但这并没有解决问题。
我相信这些方法正在生成新块,但我不是 100% 确定(这是学校的一个小组项目)
public BlockChain(int difficulty) {
this.difficulty = difficulty;
blocks = new ArrayList<>();
//create the first block
Block b = new Block(null, "Genesis Block",
System.currentTimeMillis(), 0);
b.mineBlock(difficulty);
blocks.add(b);
}
public Block newBlock(String data) {
Block latestBlock = latestBlock();
return new Block(latestBlock.getHash(), data,
System.currentTimeMillis(), latestBlock.getIndex() + 1);
}
public void addBlock(Block b) {
if (b != null) {
b.mineBlock(difficulty);
blocks.add(b);
}
}