使用nextInt()
Scanner类的方法从用户读取整数。
交换它们-
创建一个变量(临时),将其初始化为0。
将第一个数字分配给温度。
将第二个号码分配给第一个号码。
将温度分配给第二个数字。
import java.util.Scanner; public class SwapTwoNumbers { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter first number :: "); int num1 = sc.nextInt(); System.out.println("Enter second number :: "); int num2 = sc.nextInt(); int temp = 0; temp = num1; num1 = num2; num2 = temp; System.out.println("After swapping ::"); System.out.println("Value of first number ::"+ num1); System.out.println("Value of first number ::"+ num2); } }
输出结果
Enter first number :: 22 Enter second number :: 33 After swapping :: Value of first number ::33 Value of first number ::22