█微信号█ 153★8444★9023 █供卵试管婴儿████代孕选性别生男孩 ██试管包出生██代孕男孩██代孕包出生███代孕选性别██试管婴儿███代孕生男孩█████试管婴儿代孕生男孩███供卵试管婴儿代孕███
public static void move() { System.out.println("What do you want to do?"); Scanner scan = new Scanner(System.in); int userMove = scan.nextInt(); return userMove; } public static void usersMove(String playerName, int gesture) { int userMove = move(); if (userMove == -1) { break; }
通常,这可以通过更改方法签名匹配返回语句中的类型来修正错误。在这种情况下,void的实例可以改为int:
public static int move() { System.out.println("What do you want to do?"); Scanner scan = new Scanner(System.in); int userMove = scan.nextInt(); return userMove; }
阅读关于如何修复“Cannot Return a Value From Method Whose Result Type Is Void”错误的讨论。(@StackOverflow)
18.“Non-Static Variable … Cannot Be Referenced From a Static Context”
当编译器尝试从静态方法(@javinpaul)访问非静态变量时,就会发生此错误:
public class StaticTest {
private int count=0; public static void main(String args[]) throws IOException { count++; //compiler error: non-static variable count cannot be referenced from a static context } }
要修复“Non-Static Variable … Cannot Be Referenced From a Static Context”错误,可以做这两件事:
- 在签名中声明此变量为静态。
- 在静态方法中写代码创建非静态对象的实例。
阅读此介绍静态和非静态变量之间区别的教程。(@sitesbay)
19.“Non-Static Method … Cannot Be Referenced From a Static Context”
此问题发生在Java代码尝试在非静态类中调用非静态方法的情况下。 例如,以下代码:
class Sample
{
private int age;
public void setAge(int a) { age=a; } public int getAge() { return age; } public static void main(String args[]) { System.out.println("Age is:"+ getAge()); } }
将返回错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method getAge() from the type Sample
从静态方法中调用非静态方法就是声明调用非静态方法的类的实例。
阅读此关于非静态方法和静态方法之间区别的阐述。