我如何正确初始化在单独方法中创建的变量,以在另一方法中使用?

问题描述 投票:0回答:1

我已经创建了两个方法来接受用户输入,并且应该返回两个单独的变量,我想在第三个方法中调用它们。但是,我不完全了解如何将变量“链接”到第三个方法中。我还必须将所有三个方法分别设置为calculate方法,askLenaskWid

我已经尝试过一些事情,例如使用final int在不同位置声明整数,或者使用long,double等。>

 public static void main (String[] p)
  {
     askLen();
     askWid();
     calculate();
     System.exit(0);
  }

  public static int askLen ()
  {
     final int len;    
     Scanner scanner = new Scanner(System.in);
     System.out.println("What is the length of the room (in cm)?");
     len = Integer.parseInt(scanner.nextLine());
     final long l=len;
     return len;
  }

  public static int askWid ()
  {
     final int wid;    
     Scanner scanner = new Scanner(System.in);
     System.out.println("What is the width of the room (in cm)?");
     wid = Integer.parseInt(scanner.nextLine());
     final long w=wid;
     return wid;
  }

  public static int calculate ()
  {
     final int len;
     final long l;
     final int wid;
     final long w;   
     long area = (l * w) / 10000;
     System.out.println("The area is " + area + "m^2");
     double wastage = (area * 1.10) / 100;
     System.out.println("The extra you need for wastage is " + wastage + "m^2");
     double areaTotal = area + wastage;
     System.out.println("The total flooring area to order is: " + areaTotal + "m^2");
     return 1;
  }

我的预期结果是,它正确地接受了用户的整数输入并执行了我编写的算术运算,返回了上面的字符串的最终结果以及正确的计算答案。

我在编译过程中收到的错误消息是:

flooring.java:46: error: variable l might not have been initialized
         long area = (l * w) / 10000;
                      ^
flooring.java:46: error: variable w might not have been initialized
         long area = (l * w) / 10000;
                          ^
2 errors

我已经创建了两个方法来接受用户输入,并且应该返回两个单独的变量,我想在第三个方法中调用它们。但是,我不完全了解如何将变量“链接”到...

java methods
1个回答
2
投票

为什么不只是将变量传递给方法?类似于:

© www.soinside.com 2019 - 2024. All rights reserved.