Java 返回一个值。输出总是打印0
我正在学习如何返回一个值并尝试编写以下代码Java 返回一个值。输出总是打印0,java,return,Java,Return,我正在学习如何返回一个值并尝试编写以下代码 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
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
。我做错了什么?
谢谢。你应该打这个电话
int c = nganu();
分配a
和b
的输入值后。否则,在计算它们的总和时,默认情况下它们仍将包含0
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
int c = nganu();
System.out.println(c);
你应该打电话
int c = nganu();
分配a
和b
的输入值后。否则,在计算它们的总和时,默认情况下它们仍将包含0
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
int c = nganu();
System.out.println(c);
为
a
和b
赋值后,必须调用函数那么就这样说:
intc=nganu()代码>在您获得a
和b
之后 为a
和b
赋值后,必须调用函数
那么就这样说:intc=nganu()代码>在您获得a
和b
之后 请相应地更改您的代码,
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);
}
请相应地更改您的代码,
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);
}
尝试使用这一行的顺序更改:
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);
}
}
尝试使用这一行的顺序更改:
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);
}
}