做个小练习,求一个四位整数,各项位数之和
核心思想就是 利用整除(/) ,和 取模(%)来计算,代码如下:
public class Test1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt(); // 4+5+3+2
int a ,b ,c ,d ; //a = 千位 b=百位 c=十位 d=个位
a = x / 1000;
b = x / 100 % 10; // x%1000/100; (x - a*1000)/100
c = x / 10 % 10; //x%100/10 ; (x - a*1000-b*100)/10
d = x % 10;
System.out.println(a + b + c +d);
int m = 10, n = 8;
}
}
然后就是把输入的两个变量里面的值交换一下
public class Test2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//int n = 10 , m = 8;
int n = in.nextInt(),m = in.nextInt();
int temp;
temp = n ;
n = m ;
m = temp;
System.out.println("交换后"+n+","+m);
}
}