//练习1
//题目:定义一个方法,把数组{1, 2, 3}按照指定格式拼接一个字符串。格式参照如下:[word1#word2#word3]
//首先准备一个数组 int[] 内容是{1, 2, 3}
//定义一个方法,用来将数组变成字符串
//练习2
//题目:键盘输入一个字符串,并且统计其中出现的各种字符的次数
代码:
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { int[] array = {1, 2, 3}; //调用函数 System.out.println(fromArrayToString(array)); System.out.println("================================="); / Scanner s = new Scanner(System.in); System.out.println("请输入一个字符串:"); String input = s.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(ch <= 'Z' && ch >= 'A'){ countUpper ++; } else if(ch >= 'a' && ch <= 'z'){ countLower ++; } else if(ch >= '0' && ch <= '9'){ countNumber ++; } else{ countOther ++; } } //输出语句 System.out.println("大写字母有: " + countUpper); System.out.println("小写字母有: " + countLower); System.out.println("数字字符有: " + countNumber); System.out.println("其他字符有: " + countOther); } //数组转化为字符的类 public static String fromArrayToString(int[] array){ String str = "["; for (int i = 0; i < array.length; i++) { str += "word" + array[i] + "#"; if(i == array.length - 1){ str += "word" + array[i] + "#" + "]"; } } return str; } }
运行结果:
[word1#word2#word3#word3#] ================================= 请输入一个字符串: fpoegeoigjkoeprkgoe[384092340239452-3ut-29t2-[p34u-2395ui230-9F0[9KERJITGJ2Q349T0[JGERIO 大写字母有: 17 小写字母有: 26 数字字符有: 36 其他字符有: 9