“错误:在计算类中无法从静态上下文引用非静态变量”

时间:2013-09-09 13:32:50

标签: java

我编译程序时,“转换”类的实例会返回此错误。

import java.util.Scanner;

public class Convert {

    private class Conversion{

        public String getConversion(int inchInput) {
            int yards = (inchInput - (inchInput % 36)) / 36;
            int feet =  (inchInput % 36) - ((inchInput % 36) % 12);
            int inches = (inchInput % 36) % 12;

            return yards + "yards, " + feet + "feet, and " + inches + "inches.";
        }

    } // end of class Conversion

    public static void main( String[] args ) {
        Scanner scanner = new Scanner(System.in);
        int inchInput;
        Conversion conversion;
        conversion = new Conversion();

        // prompt
        System.out.println("Please enter an amout of inches (integer): ");
        inchInput = scanner.nextInt();
        String output = conversion.getConversion(inchInput);
    } // end of method main()
} // enf of class Convert

4 个答案:

答案 0 :(得分:2)

ConversionConvert的内部类。因此您无法直接访问它 您需要像这样创建Conversion个对象。

Convert convert =new Convert();
Conversion conversion;
conversion = convert.new Conversion(); 

或将Conversion声明为静态

 class Convert {
   private static class Conversion{
     ...............
      ............
  }
}

并像这样创建Conversion对象

Conversion conversion = new Convert.Conversion();

答案 1 :(得分:2)

制作Conversionstatic,以便有一个可访问的类的实例

private static class Conversion {
  ...
}

答案 2 :(得分:1)

将类的修饰符设置为静态

private static class Conversion 

at

答案 3 :(得分:0)

你可能需要:

Convert.Conversion cc = new Convert().new Conversion();
cc.getConversion(...);
...