我正在学习如何返回一个值并尝试编写以下代码;
public class JustTryingReturn {
static int a, b;
static Scanner sc = new Scanner(System.in);
static int nganu() {
return a+b;
}
public static void main(String[] args) {
int c = nganu();
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
System.out.println(c);
}
}
但输出始终打印0而不是a+b
。我做错了什么?
谢谢。
答案 0 :(得分:2)
你应该拨打电话
int c = nganu();
分配a
和b
的输入值后。否则,在计算总和时,默认情况下它们仍会包含0
。
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
int c = nganu();
System.out.println(c);
答案 1 :(得分:2)
尝试使用此更改此行的顺序:
int c = nganu();
a = sc.nextInt();
b = sc.nextInt();
喜欢这个:
public class JustTryingReturn {
static int a, b;
static Scanner sc = new Scanner(System.in);
static int nganu() {
return a+b;
}
public static void main(String[] args) {
// the order was changed
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
int c = nganu();
System.out.println(c);
}
}
答案 2 :(得分:1)
您必须在之后调用您的函数,并将值分配给a
和b
。
所以在得到int c = nganu();
和a
后,请将此b
。
答案 3 :(得分:0)
请相应更改您的代码,
public static void main(String[] args) {
//int c = nganu(); // here first time a,b is 0, still you haven't assign...
System.out.println("Enter number ");
a = sc.nextInt(); // now, actually you have assign value to a
b = sc.nextInt(); // now, actually you have assign value to b
int c = nganu();
System.out.println(c);
}