【问题标题】:Not able to resolve object error in bluej无法解决 bluej 中的对象错误
【发布时间】:2019-09-24 19:50:34
【问题描述】:

错误提示找不到变量。无法找出确切的问题。尝试在 bluej 中也重置首选项。

import java.util.*;

class Electricity
{


    public void Initialization()
     {
       int omr     = 0;
       int nmr     = 0;
       int cr      = 0;
       int rent    = 0;
       double cost = 0.0; 
       double sc   = 0.0;
    }


        public void input()
        {
            System.out.println("Enter old meter reading");
            omr = sc.nextInt();
            System.out.println("Enter new meter reading");
            nmr = sc.nextInt();
        }

        public void calculate()
        {
         cr = nmr - omr;            
        }

    public static void main()
    {
        Scanner sc = new Scanner(System.in);
    }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow,如果您的问题的答案之一是正确的,您应该接受它。

标签: java bluej


【解决方案1】:

这不是 bluej 中的错误,而是代码的问题
我猜你是学生

代码不起作用,因为变量只存在于创建它的方法中
您正在尝试访问以不同方法定义的变量。
input() 方法中,您尝试访问在Initialization() 方法中定义的变量
但它在input() 中不存在

为了让这段代码正常工作,请将所有代码放入 main() 方法中。

或者将他们使用的变量从另一个方法传递给该方法,当然您需要从 main 方法调用这些方法,但似乎您需要做更多的学习才能使第二个选项起作用。

祝你好运。

【讨论】:

    【解决方案2】:

    类似的东西。

    import java.util.Scanner;  // Import the Scanner class
    public class Main
    {
    
    
        static int calculate(int nmr, int omr)
        {
            int cr = nmr - omr;
            return cr;
        }
    
        public static void main(String[] args)
        {
    
            int omr     = 0;
            int nmr     = 0;
            // int cr      = 0;
            // int rent    = 0;
            // double cost = 0.0; 
            // double sc   = 0.0;
    
            Scanner sc = new Scanner(System.in);
    
            System.out.println("Enter old meter reading");
            omr = sc.nextInt();
            System.out.println("Enter new meter reading");
            nmr = sc.nextInt();
    
            System.out.println("The resaults: " + calculate(nmr, omr));
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 2014-04-22
      • 2018-10-23
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2018-01-05
      相关资源
      最近更新 更多