一、知识点概括
1.Object类
2.String类
3.集合
二、例题分析
1.从命令行上读入一个字符串,用两种不同的方法,把该字符串转换为一个int类型
方法一:把String直接转换为int
方法二:把String转换为Integer,再把Integer转换为int类型
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一串数字:");
//方法一:
String str = input.nextLine();
int i1 = Integer.parseInt(str);
System.out.println(i1);
//方法二:
Integer i2 = new Integer(str);
int i2 = i2.intValue();
System.out.println(i2);
}
}
2.验证邮箱“zhengcg@zparkhr.com” 是否是一个合法的邮箱格式
提示:
I.邮箱必须包含“@”和“.”
II.最后一个“.”的位置必须大于“@”的位置
public class Test1 {
public static void main(String[] args) {
String s = "zhengcg@zpargkm.com";
int check1 = s.indexOf("@");
int check2 = s.indexOf(".");
if (check1 != -1 && check2 != -1 && check1 < check2){
System.out.println("邮箱合法");
}else{
System.out.println("邮箱不合法");
}
}
}
3.给定一个由数字组成的字符串
如:“1239586838923173478943890234092”;统计出每个数字出现的次数
public class Test1 {
public static void main(String[] args) {
String s = "1239586838923173478943890234092";
char[] c = s.toCharArray();
for (int i = 0;i <= 9;i++){
int count =0;
for (int j = 0; j < c.length; j++) {
if (i == c[j]-48){
count++;
}
}
System.out.println(i+"出现的次数是:"+count+"次");
}
}
}
4.(Map)利用Map,完成下面的功能:
1)从命令行读入一个字符串,表示一个年份,输出该年的世界杯冠军是哪支球队。
如果该年没有举办世界杯,则输出:没有举办世界杯。
2)增加功能:
读入一支球队的名字,输出该球队夺冠的年份列表。
例如:
I.读入“巴西”,应当输出1985、1962、1970、1994、2002
II.读入“荷兰”,应当输出“没有获得过世界杯”
附录:截至2009年,历届世界杯冠军、世界杯冠军以及对应的夺冠军年份:
import java.util.HashMap;
import java.util.Scanner;
public class WorldCup {
public static void main(String[] args) {
java.util.Map<String, String> m1 = new HashMap<>();
m1.put("2006", "意大利");
m1.put("2002", "巴西");
m1.put("1998", "法国");
m1.put("1994", "巴西");
m1.put("1990", "德国");
m1.put("1986", "阿根廷");
m1.put("1982", "意大利");
m1.put("1978", "阿根廷");
m1.put("1974", "德国");
m1.put("1970", "巴西");
m1.put("1966", "英格兰");
m1.put("1962", "巴西");
m1.put("1958", "巴西");
m1.put("1954", "德国");
m1.put("1950", "乌拉圭");
m1.put("1938", "意大利");
m1.put("1934", "意大利");
m1.put("1930", "乌拉圭");
//1
Scanner input = new Scanner(System.in);
System.out.println("请输入一个年份:");
String year = input.nextLine();
if (m1.containsKey(year) == false) {
System.out.println(year + "年没有举办世界杯");
} else {
System.out.println(year + "年的世界杯冠军球队是:" + m1.get(year));
}
//2
Scanner input2 = new Scanner(System.in);
System.out.println("请输入一支球队的名字:");
String team = input2.nextLine();
if (m1.containsValue(team) == false) {
System.out.println(team + "没有获得过世界杯");
} else {
System.out.println(team + "队的夺冠年份是:");
for (String k : m1.keySet()) {
if (m1.get(k).equals(team)) {
System.out.print(" " + k);
}
}
}
}
}