在学习java基础的时候遇到的编程练习题,分享一下
1.(一)键盘录入一个字符串,统计字符串中各种内容:
a)小写字母=
b)大写字母=
c)数字字符=
d)其他字符=
e)把结果放入Map集合
public static void main(String[] args) {
//从键盘中输入字符串
Scanner scanner= new Scanner(System.in);
System.out.println("请输入字符串:");
String str =scanner.next();
int lower = 0;//小写字符的数量
int biger = 0;//大写字符的数量
int num =0;//数字字符的数量
int other=0;//其他字符
for (int i = 0; i <str.length(); i++) {
char ch = str.charAt(i);
if (ch>=65 && ch <=96) {
biger++;
}else if (ch>=97&&ch<=122) {
lower++;
}else if (ch>=48&&ch<=57) {
num++;
}else {
other++;
}
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("小写的数量是:", lower);
map.put("大写的数量是:", biger);
map.put("数字的数量是:", num);
map.put("其他的数量是:", other);
System.out.println(map);
}
2.(二)创建ArrayList集合,创建学生类
a)存入6个学生对象,有姓名、年龄、地址属性
b)使用6种方式遍历List集合
public static void main(String[] args) {
ArrayList<Student> stus = new ArrayList<Student>();
stus.add(new Student("张三", 10, "郑州"));
stus.add(new Student("李四", 78, "湖南"));
stus.add(new Student("王五", 45, "杭州"));
stus.add(new Student("赵六", 23, "郑州"));
stus.add(new Student("田七", 85, "非洲"));
stus.add(new Student("李华", 20, "北京"));
stus.add(new Student("张华", 25, "南京"));
System.out.println(stus);
System.out.println("=========1.直接遍历===============");
// 方式一
System.out.println(stus.get(0));
System.out.println(stus.get(1));
System.out.println(stus.get(2));
System.out.println(stus.get(3));
System.out.println(stus.get(4));
System.out.println(stus.get(5));
System.out.println("=========2.for循环==============");
for (int i = 0; i < stus.size(); i++) {
System.out.println(stus.get(i));
}
System.out.println("==========3.while循环================");
int i = 0;
while (i < stus.size()) {
System.out.println(stus.get(i));
i++;
}
System.out.println("===========4.do-while循环=========");
int index = 0;
do {
System.out.println(stus.get(index));
index++;
} while (index < stus.size());
System.out.println("========5.foreach循环=======");
for (Object obj : stus) {
System.out.println(obj);
}
System.out.println("===========6.Iterator=============");
Iterator<Student> it = stus.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}