Java TestPassByvalue
我正在为学校编写这段代码,但它告诉我修改main方法,这样在调用swap方法之后,num1和num2的实际值在main中交换,并在输出中显示出来。不要简单地更改print或println语句中两个数字的顺序,您必须在main方法中包含交换代码。在交换后,您的输出将有一行显示main中两个数字的值。请参阅下面蓝色文本中的新输出行。我怎么能这样做 我的代码在下面Java TestPassByvalue,java,eclipse,Java,Eclipse,我正在为学校编写这段代码,但它告诉我修改main方法,这样在调用swap方法之后,num1和num2的实际值在main中交换,并在输出中显示出来。不要简单地更改print或println语句中两个数字的顺序,您必须在main方法中包含交换代码。在交换后,您的输出将有一行显示main中两个数字的值。请参阅下面蓝色文本中的新输出行。我怎么能这样做 我的代码在下面 public class TestPassByValue { /** Main method */ public static void
public class TestPassByValue {
/** Main method */
public static void main(String[] args) {
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " + num1 + " and num2 is " + num2);
// invoke the swap method to attempt to swap two variables
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " + num1 + " and num2 is " + num2);
}
/** Swap two variables */
public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");
System.out.println("\t\tBefore swapping, n1 is " + n1 + " and n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping, n1 is " + n1 + " and n2 is " + n2);
}
}您的问题的文本标题不清楚,但如果您想在main方法内的第二个print语句中打印以打印交换的值 System.out.println(“调用swap方法后,num1为“+num1+”,num2为“+num2”) 然后,您必须创建一个新类,该类中的int值作为字段。并使用此对象,而不是使用原始int变量num1和num2。 乙二醇
如果您不希望这样,那么您可以通过在main中的第二个print语句中打印相同的值num1=1和num2=2来编写代码。。您所指的“蓝色文本中的下一行”是什么?
class MyInteger{
int i;
MyInteger(int i){
this.i = i;
}
}