1.输入一个字符串,输出字符串中的字母、数字以及其他符号的个数.
package Mai3;
import java.util.Scanner;
public class Demo9 {
public static void main(String[] args) {
String IString = null; //字符串
int StringLength = 0; //字符串长度
int latterNum = 0; //字母的个数
int numberNum = 0; //数字的个数
int otherNum = 0; //其他字符的个数
char currentChar; //当前字符
Scanner Scanner = new Scanner(System.in);
System.out.println("输入字符串:");
IString = Scanner.nextLine(); //输入字符串
StringLength = IString.length();
for(int i = 0;i < StringLength;i++) { //挨个取每个字符
currentChar = IString.charAt(i); //取得字符串位置i的字符
if((currentChar >= 'a' && currentChar <= 'z' )|| (currentChar >= 'A' &&
currentChar <= 'Z')) {
latterNum++;
}
else if(currentChar >= '0' && currentChar <= '9') {
numberNum++;
}
else {
otherNum++;
}
}
System.out.println("输入字符串:" + IString);
System.out.println("字母个数 = " + latterNum);
System.out.println("数字个数 = " + numberNum);
System.out.println("其他字符个数 = " + otherNum);
}
}
运行结果为:
输入字符串:
Mihrar·omarjan~2024.3.17! &&
输入字符串:Mihrar·omarjan~2024.3.17! &&
字母个数 = 13
数字个数 = 7
其他字符个数 = 8
2.判断水仙花数.
注:水仙花数指一个三位整数的个位、十位、百位3个数的立方和等于该数本身.
package Mai3;
import java.util.Scanner;
public class Demo10 {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int a,b,c;
int num;
num = Scanner.nextInt();
a = num / 100;
b = num % 100 / 10;
c = num % 10;
if(num == (a * a * a + b * b * b + c * c * c)) {
System.out.println(num + "是水仙花数");
}
else {
System.out.println(num + "不是水仙花数");
}
}
}
运行结果为:
407
407是水仙花数
480
480不是水仙花数