Java打印main方法中的递归
我想知道当我试图在main中打印递归的值时,答案是: 输入数字:1 2结果是: 如何使数字2朝前移动 结果是:2Java打印main方法中的递归,java,Java,我想知道当我试图在main中打印递归的值时,答案是: 输入数字:1 2结果是: 如何使数字2朝前移动 结果是:2 import java.util.Scanner; public class Question4Final { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the number:
import java.util.Scanner;
public class Question4Final {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
System.out.printf("The result is: ", multiplication(a));
}
public static int multiplication(int a) {
if (a == 5) {
int multiply = 10 * 6 * 2;
System.out.print(multiply);
} else if (a == 4) {
int multiply2 = 6 * 2;
System.out.print(multiply2);
} else if (a == 1) {
System.out.print("2");
}
return a;
}
}
要调用该方法,请执行以下操作:
System.out.printf("The result is: ", multiplication(a));
首先必须对参数求值,以便在System.out.printf(“结果是:”,乘法(a))
之前执行乘法(a)
。由于乘法(a)
打印某物,因此打印发生在打印“结果是:”之前
您应该更改乘法(a)
,只返回结果而不打印它。然后使用System.out.println(“结果是:“+乘法(a))
打印结果
请注意,您必须更改通过乘法(a)
返回的值,因为当前您返回的a
,该值不是该方法打印的值。要调用该方法:
System.out.printf("The result is: ", multiplication(a));
首先必须对参数求值,以便在System.out.printf(“结果是:”,乘法(a))
之前执行乘法(a)
。由于乘法(a)
打印某物,因此打印发生在打印“结果是:”之前
您应该更改乘法(a)
,只返回结果而不打印它。然后使用System.out.println(“结果是:“+乘法(a))
打印结果
请注意,您必须更改通过
乘法(a)
返回的值,因为当前您返回的a
,该值不是该方法打印的值。您的代码中有两个问题
2The result is:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
以下是不同选项的输出:
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2
您的代码中有两个问题
2The result is:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int a = scan.nextInt();
int product = multiplication(a);
System.out.println("The result is : " +product);
}
public static int multiplication(int a){
int multiply = 0;
if(a == 5){
multiply = 10 * 6 * 2;
}else if(a == 4){
multiply = 6 * 2;
}else if(a == 1){
multiply = 2;
}
return multiply;
}
}
以下是不同选项的输出:
Enter the number: 4
The result is : 12
Enter the number: 5
The result is : 120
Enter the number: 1
The result is : 2
这非常有帮助,这将是我的荣幸。@SankyJohn:如果我的答案对你有效,请接受我的答案,如果你喜欢它和解释,可以投一票。这非常有帮助,这将是我的荣幸。@SankyJohn:如果我的答案对你有效,请接受我的答案,如果你喜欢它和解释,可以投一票。