练习-指定格式拼接字符串和统计输入的字符串中各种字符的个数
练习-指定格式拼接字符串
题目:
定义一个方法,把数组{1,2,3}按照指定格式拼接成一个字符串。格式参照如下:[ word1#word2#word3 ]
public static void main(String[] args) { int[ ]array = {1,2,3}; String result = fromArrayTostring( array ) ; System.out.println(result); } public static String fromArrayTostring(int[ ] array) { String str = "["; for (int i = 0; i < array.length; i++) { if (i == array.length - 1) { str += "word" + array[i] + "]"; } else { str = "word" + array[i] + "#"; } } return str; }
练习-统计输入的字符串中各种字符的个数
题目:
键健盘输入一个字符串,并且统计其中各种字符出现的次数。种类有:大写字母、小写字母、数字、其他
public static void main(String[ ]args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串:"); String input = sc.next();//获取键盘输入的一个字符串 int countUpper = 0; //大写字母 int countLower = 0;//小写字母 int countNumber = 0; //数字 int countOther = 0; //其他字符 char[] charArray = input.toCharArray(); for (int i = 0; i < charArray.length; i++) { char ch = charArray[i]; //当前单个字符 if ('A' <= ch && ch <= 'Z') { countUpper++; } else if ('a' <= ch && ch <= 'z') { countLower++; } else if ('0' <= ch && ch <= '9') { countNumber++; } else { countOther++; } System.out.println("大写字母有:" + countUpper); System.out.println("小写字母有:" + countLower); System.out.println("数字有:" + countNumber); System.out.println("其他字符有:" + countOther); } }

浙公网安备 33010602011771号