【发布时间】:2015-08-08 19:23:10
【问题描述】:
在处理整数的 java 中,我无法掌握四种不同的返回语句问题。它们通常以“神秘”和“谜”的名义出现。我已经尝试过无数次解决它们,而网络和我的教科书不包含任何类似的示例供我使用。我的直觉是我在逻辑上遗漏了一些东西。如果有人可以解释这些问题(最好是最难的问题),我相信我会理解的。如果格式不符合本站要求,我提前致歉,因为这是我第一次发帖。
1 public class Program 1{
2
3 public static int y = 2;
4
5 public static int mystery(int x, int y) {
6 y = y + x;
7 return x + y;
8 }
9
10 public static void main(String[] args) {
11 int x = 1;
12 x = mystery(x, y);
13 y = mystery(y, x);
14 System.out.println(x + " " + y);
15 }
16}
17 // Answer : 4 8
I get x to be 4, but I struggle to get y to be 8.
1 public class Program 2{
2
3 public static int y = 2;
4
5 public static int mystery(int a, int b) {
6 y = b + a;
7 return a + b;
8 }
9
10 public static void main(String[] args) {
11 int x = 1;
12 x = mystery(x, y);
13 y = mystery(y, x);
14 System.out.println(x + " " + y);
15 }
16}
17 // Answer : 3 6
I get x to be 3, but I struggle to get y to be 6.
1 public class Program 3{
2
3 public static int x = 1;
4 public static int y = 2;
5
6 public static int mystery1(int a, int b) {
7 x = a + b;
8 return b + a;
9 }
10
11 public static int mystery2(int a, int b) {
12 y = b + a;
13 x = mystery1(a, b);
14 return a + b;
15 }
16
17 public static void main(String[] args) {
18 x = mystery2(x, y);
19 System.out.println(x + " " + y);
20 }
21
22}
23 // Answer : 3 3
I get x to be 3, but I struggle to get y to be 3.
public class Enigma {
public static int x = 1;
public static int y = 2;
public static int n = 0;
public static int aaa(int a, int b) {
n++;
return a + b;
}
public static int bbb(int a, int b) {
n++; x = aaa(x, a); y = aaa(y, b);
return x + y;
}
public static void ccc(int x, int q) {
n++; x = bbb(1, x); y = bbb(2, q);
}
public static void main(String[] args) {
int x = aaa(3, y);
y = bbb(x, y); ccc(x, 1);
System.out.println(x + " " + y + " " + n);
// Answer : 5 25 11
I get x to be 5, but I struggle to get y = 25 and n = 11, although incrementing n at each method is probably the reason why.
【问题讨论】:
-
您在程序 1 的
mystery方法中使用一个也称为y的参数来隐藏您的类变量y。 -
类名应该是一个单词(目前不是两个)
-
是的,我知道,为了便于阅读,我在发帖前将其隔开。
标签: java methods static integer return