在JAVA中,将CHAR类型转换为INT类型;
方法
char a = '1';
int b = a - '0';
接下来看实例:
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:
153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
public class Prog3 { public static void main(String[] args){ int count = 0; for(int n = 100; n < 1000; n++){ if(isLouts(n)){ count++; System.out.print(n + " "); } } System.out.println(""); System.out.println(count); } public static boolean isLouts(int n){ boolean flag = false; int count = 0; String str1 = n + ""; for(int i = 0; i < str1.length(); i++){ //通过String.charAt()方法得到每位的数字,利用char -'0'将char转换为int类型,达到得到每位数字的目的; count = (str1.charAt(i) - '0') * (str1.charAt(i) - '0') * (str1.charAt(i) - '0') + count; } if(count == n){ flag = true; } return flag; } }
