【问题标题】:Count in class with static variable使用静态变量在类中计数
【发布时间】:2018-12-03 17:20:35
【问题描述】:

我的代码是假设创建便笺和写消息,一天中的时间和计算对象。 (post1、post2、post3 等)

import java.time.LocalTime;

public class Post_it {
    private String note;
    static int number=0;

    private LocalTime ltime; 

    public Post_it(String note_, LocalTime time) {
        this.note = note_;
        this.ltime = time;
        number++;
    }
}

我尝试使用打印

public static void main(String[] args) {

    Post_it post1 = new Post_it("Text text text");
    Post_it post2 = new Post_it("Text Text");
    Post_it post3 = new Post_it("Text");

    System.out.println(Post_it.numbers);
}

但我无法打印它,它抱怨 Post_it.numbers。可以打印 post1.numbers 但即使我打印 post2.numbers 我总是得到 0。

【问题讨论】:

  • 您在每次实例化对象时重新初始化静态属性。不要!
  • 抱怨是什么意思?
  • 您的构造函数需要两个参数。你只通过了一个。 阅读您收到的错误消息。它们意味着什么。
  • 能否列出您收到的错误信息?
  • 静态变量是number 而不是numbers,你的代码中有很多错误;) 阅读所有评论以修复它们

标签: java class counter


【解决方案1】:

正如arkascha 已在 cmets 中所述,每次创建新对象时都会覆盖计数器。但这不是您代码中的唯一错误。

您收到以下错误:The constructor Post_it(String) is undefined,这意味着编译器无法找到 Post_it 的构造函数,而 String 是唯一的参数。

您可以通过在构造函数调用中添加LocalTime 来解决此问题:

new Post_it("Text text text", LocalTime.now())

现在到您的柜台 - 您已将变量定义为 number 但访问 Post_it.numbers 这不太正确。显然必须是Post_it.number

但是,您可以使用 List 删除静态计数器,因为它并没有像您那样定义变量。这就是存在ListArray 之类的东西的原因。我只是稍微修改了您的代码,这是我的方法:

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

public class Post_it
{
private String note;

private LocalTime time;

public Post_it(String note, LocalTime time)
{
    this.note = note;
    this.time = time;
}

public static void main(String[] args)
{
    List<Post_it> posts = new ArrayList<>();
    posts.add(new Post_it("Text text text", LocalTime.now()));
    posts.add(new Post_it("Text Text", LocalTime.now()));
    posts.add(new Post_it("Text", LocalTime.now()));
    System.out.println(posts.size());
}

}

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多