练习题1:手机选号:根据用户输入的手机号来确认用户实际支付的价格
如果尾数为 8,需支付办卡费 50 元
如果尾数为 4,需支付办卡费用 0 元
如果是其他尾号, 需支付办卡费用 20 元
package demo;
import java.util.Scanner;
public class D1 {
public static void main(String[] args) {
System.out.println("请输入电话号码");
Scanner s=new Scanner(System.in);
String tel=s.nextLine();//String类型数据一般用nextLine()
getPrice(tel);
}
public static void getPrice(String tel){
if(tel.length()!=11){//判断手机号tel的长度
System.out.println("格式不正确");
return ;
}
int price;
char c=tel.charAt(10);//charAt(int index),返回指定索引处的字符
switch (c){
case 8:
price=50;
break;
case 4:
price=0;
break;
default:
price=20;
}
System.out.println("需支付办卡费用"+price+"元");
}
}
请输入电话号码
12345678910
需支付办卡费用20元
练习题2: 求任意自然数各位数之和
接收用户输入的任意自然数, 累计所有位数数字之和
package demo;
import java.util.Scanner;
public class D3 {
public static void main(String[] args) {
System.out.println("输入自然数");
long l=new Scanner(System.in).nextLong();
long sum=0;
while (l!=0) {
sum = sum+l%10;//l%10 最后一位的值
l = l / 10;//小数点后舍掉,减一位
}
System.out.println(sum);
}
}
输入自然数
123
所有位数数字之和为6
练习题3:将任意自然数各位数的平方组成一个新的数
如:
输入4114
输出161116
因为42为16,12为1。
public class Demo01 {
public static void main(String[] args) {
System.out.println(squareDigits(4114));
}
public static int squareDigits(int n) {
String a="";
int b=0;
while(n!=0){
a=((n%10)*(n%10))+a;
n=n/10;
}
try {
b = Integer.parseInt(a);
}catch (NumberFormatException e){
}
return b;
}
}
161116