在新方法中初始化变量

时间:2014-02-10 16:24:05

标签: java

import java.util.Scanner;

public class ExponentExperiment
{
    public static void main(String [] args)
    {
        int numberOne;
        int B;
        int C;
        Scanner keyBoard = new Scanner(System.in);
        System.out.println("Enter an Integer");
        numberOne = keyBoard.nextInt();
        jordan(numberOne, B);
        carter(numberOne, B, C);
        System.out.println(numberOne + " squared is " + B);
        System.out.println(numberOne + " cubed is " + C);
    }
    public static int jordan(int numberOne, int B)
    {
        B = numberOne * numberOne;
    return B;

    }
    public static int carter(int numberOne, int B, int C)
    {
            C = B * numberOne;
    return C;

    }

}

错误:

H:\ ExponentExperiment.java:13:变量B可能尚未初始化         约旦(numberOne,B);                           ^ H:\ ExponentExperiment.java:14:变量C可能尚未初始化         卡特(numberOne,B,C);                              ^ 2个错误

工具已完成,退出代码为1

3 个答案:

答案 0 :(得分:1)

为什么不直接使用您的返回值?

import java.util.Scanner;

public class ExponentExperiment
{
    public static void main(String [] args)
    {
        int numberOne;
        int b = 0;
        int c = 0;
        Scanner keyBoard = new Scanner(System.in);
        System.out.println("Enter an Integer");
        numberOne = keyBoard.nextInt();
        b = jordan(numberOne);
        c = carter(numberOne, b);
        System.out.println(numberOne + " squared is " + b);
        System.out.println(numberOne + " cubed is " + c);
    }
    public static int jordan(int numberOne)
    {
        return (numberOne * numberOne);
    }

    public static int carter(int numberOne, int b)
    {
            return (b * numberOne);
    }
}

答案 1 :(得分:0)

在Java中,简单类型的变量是按值传递的,所以它永远不会起作用。 请参阅:Is Java "pass-by-reference" or "pass-by-value"?

答案 2 :(得分:-1)

你有int B;和int C;在主要方法的顶部,执行

  int B = 0; 
  int C = 0; 

所以他们被初始化了。