Java,非静态无法引用静态上下文 [英] Java, non-static cannot be reference to static context

查看:192
本文介绍了Java,非静态无法引用静态上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UNI atm做Java课程,我遇到了一个骰子问题。

Doing Java course, at UNI atm, and I'm having a bit of trouble with a dice-problem.

我有以下内容:

 public class Die {
   public int eyes;
   private java.util.Random r;
   private int n;

   public Die (int n) {
     r = new Random();
     this.n = n;
   }

   public void roll() {
     eyes = r.nextInt(Die.n);
   }

编译时我得到:非静态变量n不能从静态引用上下文。我如何解决这个问题,同时从用户给定的值中随机化?

When compiling I get: non-static variable n cannot be referenced from a static context. How would I go about fixing this, whilst having it randomize from a user given value?

推荐答案

n 不是静态变量,因此您无法以静态方式引用它( Die.n )。

n is not a static variable, so you cannot refer to it in a static manner (Die.n).

因为它是 Die 类中的实例变量,而你在<$ c中引用它$ c>死类,您只需使用 n 而不是 Die.n

Since it is an instance variable in the Die class, and you are referring to it in the Die class, you can just use n instead of Die.n.

这篇关于Java,非静态无法引用静态上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆