Q9
7.从命令行上读取一个字符串,用两种不同的方法,把字符串转换为一个int类型
方法一:把String直接转换为Int
方法二:把String转换为Integer,再把Integer转换为int类型
public class Test07 {
public static void main(String[] args) {
String s = "123";
int s2 = Integer.parseInt(s);
Integer s3 = Integer.valueOf(s);
int s4 = s3;// 自动拆箱
System.out.println(s);
System.out.println(s2);
System.out.println(s3);
}
}
- ABC
当一个对象与一个字符串相加时, 会自动调用对象的 toString 方法, 从而把该对象转化为字符串, 再进行字符串的连接。A/B/C 三个选项, 最终都会成为“字符串+对象” 的形式, 因此编译都能通过D 选项错误, 因为 stu+100 做的是对象和一个整数的加法, 这种运算没有定义, 因此编译不通过。
public class Test08 {
public static void main(String[] args) {
Student stu1 = new Student("tom",18);
System.out.println(stu1+" "+100);
System.out.println(100+" "+stu1);
System.out.println(" "+100+stu1);
//System.out.println(stu1+100+" ");//编译报错
}
}
class Student{
private int age;
private String name;
public Student() {}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name+" "+age;
}
}
11.获取邮箱“zhengcg@zparkhr.com”中的用户名“zhengcg”
public class Test11 {
public static void main(String[] args) {
String mailbox = "zhengcg@zparkhr.com";
System.out.println(mailbox.substring(0, mailbox.indexOf("@")));
}
}
运行结果:
zhengcg
12.验证邮箱“zhengcg@zparkhr.com”是否是一个合法的邮箱格式
提示:
1. 邮箱必须包含“@”和“.”
2. 最后一个“.”的位置必须大于“@”的位置
public class Test12 {
public static void main(String[] args) {
String mailbox = "zhengcg@zparkhr.com";
if(mailbox.contains("@") && mailbox.contains(".com") &&
mailbox.endsWith(".com") && mailbox.indexOf("@")>0 &&
mailbox.indexOf("@")<mailbox.indexOf(".")) {
System.out.println("邮箱格式正确");
}else {
System.out.println("对不起,您的邮箱格式不合法");
}
}
}
运行结果:
邮箱格式正确
13.将随机获取的UUID(含义是通用唯一识别码Universally Unique Identifier)中的“-”去掉
提示:java.util.UUID.randomUUID().toString()//可以获取随机UUID
格式:e6c57443-1667-4d75-98f6-a8863d95e58f
public class Test13 {
public static void main(String[] args) {
String s = java.util.UUID.randomUUID().toString();
System.out.println(s);
System.out.println(s.replace("-", " "));
}
}
运行结果:
14.在给定的字符串“ABCDEFGhijklmn1234567”中获取随机的4个字符,并使用StringBuilder拼接成字符串。(随机获取到的4个字符中可以出现重复字符)
提示:创建随机数对象java.util.Random。
java.util.Random random = new java.util.Random();
random.nextInt(100);//可以获取到0~99中任意一个随机数
public class Test14 {
public static void main(String[] args) {
java.util.Random random = new java.util.Random();
String s = "ABCDEFGhijklmn1234567";
for (int i = 0; i < 4; i++) {
int d = random.nextInt(21);
Character c = s.charAt(d);
String s2 = c.toString();
StringBuilder s3 = new StringBuilder();
System.out.print(s3.append(s2));
}
}
}
运行结果:
G3D1
F47m
iA3l
15.给定一个由数字组成的字符串
如:“1239586838923173478943890234092” ;统计出每个数字出现的次数。
public class Test15 {
public static void main(String[] args) {
for (Integer i = 0; i < 10; i++) {
int c = 0;
String s = "1239586838923173478943890234092";
while (s.indexOf(i.toString()) >= 0) {
s = s.substring(s.indexOf(i.toString()) + 1, s.length());
c++;
}
System.out.println(i + "出现的次数为:" + c + "次");
}
}
}
运行结果: