2

我有一个没有返回正确答案的 java 程序,我不知道为什么。这是代码:

public class hello {
    public static void main(String[] args) {
        int a =5;
        doubleNumbers(a);
        System.out.println(" 5 doubled is:"+a);
    }

    private static void doubleNumbers(int a) {
        a = 5*2;
    }
}

这是我在 helloWorld 之后的第一个 java 程序。

4

8 回答 8

6

Java 是按值传递的,这意味着传递给函数的变量不会在函数之外更改。

由于这是作业,我不会向您展示解决方案,而只是告诉您返回计算的值。

于 2012-05-30T12:12:16.347 回答
3

you're not returning anything from your method

change it to

 private static int doubleNumbers(int a) { 
return a * 2; 
 } 
于 2012-05-30T12:11:45.647 回答
1

I would change the method doubleNumbers to return the result of the calculation, so it would look something like this:

private static void doubleNumbers(int a) {
    return a*2;
}

And then change the lines in the main method:

int a = 5;
a = doubleNumbers(a);

Also, doubleNumbers would only ever return 10 in the original implementation. You need to use the a variable you passed in, as the above code shows.

于 2012-05-30T12:14:20.443 回答
1

您的代码有两个问题。首先,您应该更改 doubleNumbers 方法以返回某些内容,接下来您应该将 print 语句更改为打印返回值的位置。

例如(在伪代码中,所以你必须考虑一下!):

method doCalculation{
....
return calculated answer
}

main{
....
Print(doCalculation)
}
于 2012-05-30T12:19:54.577 回答
0

primitive types in Java passed by value not by reference. You need Object-type to pass it by reference try this:

 private static void doubleNumbers(Integer a) {
a = a*2;
 }
于 2012-05-30T12:13:39.290 回答
0

There are 2 obvious problems:

  1. You do not assign the return value of doubleNumbers() to any variable.
  2. doubleNumbers() does not return a value (replace voidwith int)
于 2012-05-30T12:14:15.020 回答
0
public class hello {


     public static void main(String[] args) 
     {
       int a =5;
       a = doubleNumbers(a);

       System.out.println(" 5 doubled is:"+a);

     }

     private static int doubleNumbers(int a) {
       return a*2;
     }

}

每个变量都有一个上下文,默认情况下仅限于使用它的函数。

adoubleNumbers()功能与第一个不同。

您需要返回结果,并将其分配给您的原始a变量

于 2012-05-30T12:14:37.453 回答
0

更好的方法是将 double Numbers() 方法从 更改void为 ,int以便它可以返回,也不是仅a打印 ,而是打印该方法,因为现在它将加倍a. 我还添加了扫描仪,因此程序不仅可以加倍 5,还可以输入任何数字。

public class Hello {
  public static void main(String[] args) {
    Scanner myScn = new Scanner(System.in);
    System.out.println("Please enter a number: ");
    int a = myScn.nextInt();
    //doubleNumbers(a);
    System.out.println(a+ " doubled is:"+doubleNumbers(a));

  }

  private static int doubleNumbers(int a) {
    int x = a*2;
        return x;
  }
}
于 2012-05-30T14:20:12.683 回答