Java 程序交换两个数字。
javaobject oriented programmingprogramming更新于 2024/4/11 1:48:17
在本文中,我们将了解如何在 Java 中交换两个数字。这是使用临时变量完成的。
下面是相同的演示 −
输入
假设我们的输入是 −
value_1 : 45 value_2 : 70
输出
所需的输出将是 −
value_1 : 70 value_2 : 45
算法
步骤 1- 开始 步骤 2- 声明三个整数:value_1、value_2 和 temp 步骤 3- 读取值 步骤 4- 将 value_1 分配给临时变量 步骤 5- 将 value_2 分配给 value_1 步骤 6- 将临时变量分配给value_2 步骤 6- 显示两个值 步骤 7- 停止
示例 1
import java.util.Scanner;
public class NumbersSwap{
public static void main(String[] args){
int value_1, value_2, my_temp;
System.out.println("The required packages have been imported");
Scanner my_scan = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.println("Enter the first number");
value_1 = my_scan.nextInt();
System.out.println("Enter the second number");
value_2 = my_scan.nextInt();
System.out.println("----Before swap----");
System.out.println("The first value is " + value_1 + " and the second value is " + value_2 );
my_temp = value_1;
value_1 = value_2;
value_2 = my_temp;
System.out.println("----After swap----");
System.out.println("The first value is " + value_1 + " and the second value is " + value_2 );
}
}
输出
The required packages have been imported A scanner object has been defined Enter the first number 112 Enter the second number 34 ----Before swap---- The first value is 112 and the second value is 34 ----After swap---- The first value is 34 and the second value is 112
示例 2
public class NumbersSwap{
public static void main(String[] args){
int value_1 , value_2, my_temp;
System.out.println("The required packages have been imported");
value_1 = 45;
value_2 = 70;
System.out.println("----Before swap----");
System.out.println("The first number is " + value_1 + " and the second number is " + value_2 );
my_temp = value_1;
value_1 = value_2;
value_2 = my_temp;
System.out.println("----After swap----");
System.out.println("The first number is " + value_1 + " and the second number is " + value_2 );
}
}
输出
The required packages have been imported ----Before swap---- The first number is 45 and the second number is 70 ----After swap---- The first number is 70 and the second number is 45
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

