table of Contents
1. The purpose of the experiment
1. According to the ID card to determine whether it is birthday
2. Extract the numbers in the string
4. String to achieve case conversion
5. String encryption and decryption
11. Programming to simulate user registration function
The official Java help manual document, click here to download
1. The purpose of the experiment
1. Master the use of String and StringBuffer;
2. Master the use of packaging;
3. Master the use of collections List, Set and Map;
4. Master the use of Iterator;
5. Understand the role of generics and basic usage.
2. Experimental code
1. According to the ID card to determine whether it is birthday
Write a program: input an 18-digit ID number, and then judge whether the birthday has passed according to the date of birth information? And output one of the following three messages.
This year's birthday has passed.
This year's birthday has not passed.
Today is birthday.
package 作业练习.test3;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Birthday {
public static void main(String[] args) {
System.out.println("输入您的身份证号:");
Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
String[] sNum ={str};
int[] birthTime = new int[1];
birthTime[0] = Integer.parseInt(sNum[0].substring(10, 14));
SimpleDateFormat sdf = new SimpleDateFormat("MMdd");//设置格式
Date date = new Date();//表示当前时间,无法单独输出
int now = Integer.parseInt(sdf.format(date));//方法
System.out.println(now);
// 输出
for (int i = 0; i < 1; i++) {
System.out.println(sNum[i]);
if (now > birthTime[i]) {
System.out.println("This year's birthday has passed.");
} else if (now < birthTime[i]) {
System.out.println("This year's birthday has not passed.");
} else if (now == birthTime[i]) {
System.out.println("Today is birthday.");
}
}
}
}
2. Extract the numbers in the string
Write a program to remove all non-digital characters in a string, for example: remove all non-digital characters in the form " A1BC2you3 ", get the string " 123 ", and convert " 123 " to int type and output it, if input If there are no numbers in the string, "no number" is output.
package 作业练习.test3;
import java.util.Scanner;
public class StringToInt {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
String newStr = "\\D+";//\d 是一个正字表达式,标识所有数字及0-9
str = str.replaceAll(newStr, "");
if (str.length() > 0) {
int n = Integer.parseInt(str);//parseInt() 方法用于将字符串参数作为有符号的十进制整数进行解析。
System.out.println(n);
} else {
System.out.println("无数字");
}
}
}
3. ID card hidden information
Write a program to display the year information in the 18 -digit ID number certificate number as * , and the rest of the characters remain unchanged (for example, the ID number 10013319961213602X is converted to 100133****1213602X for display).
Note: Please use the methods of StringBuffer and String respectively .
package 作业练习.test3;
import java.util.Scanner;
public class Shenfenzheng {
public static void main(String[] args) {
System.out.println("输入您的身份证号:");
Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
StringBuilder sb = new StringBuilder(str);
sb.replace(6, 10, "****");
System.out.println(sb.toString());
}
}
4. String to achieve case conversion
Write the program to achieve, the uppercase and lowercase letters are switched, and the other characters remain unchanged (for example: input the string " I love Java !" and the output is " i LOVE jAVA !").
package 作业练习.test3;
import java.util.Scanner;
public class Upper {
public static void main(String [] args)
{
System.out.println("输入字符:");
String str1 = new Scanner(System.in).nextLine(); //输入字符串
String str2 = new String();
char ch;
for(int i=0;i<str1.length();i++)
{
if(Character.isUpperCase(str1.charAt(i)))
{
ch = Character.toLowerCase(str1.charAt(i));
str2+=ch;
}else if(Character.isLowerCase(str1.charAt(i)))
{
ch =Character.toUpperCase(str1.charAt(i));
str2+=ch;
}else
{
ch =str1.charAt(i);
str2+=ch;
}
}
System.out.println(str2);
}
}
5. String encryption and decryption
Please design a class to encapsulate two static methods, namely the string encryption method and the string decryption method. Claim:
After encrypting a specified string, the ciphertext can be decrypted using the decryption method number, and the plaintext information can be displayed. The way of encryption is to add each character in the string to its position in the string and an offset value of 5 . Take the string " china " as an example, the position of the first character " c " in the string is 0 , then its corresponding ciphertext is " 'c'+0+5" , which is h . According to this rule, the string " china " is encrypted as " hnpvj " .
package 作业练习.test3;
import java.util.Scanner;
public class Jiami {
public static void main(String [] args)
{
Scanner scan =new Scanner(System.in);
char secret ='8';//加密文字符
System.out.println("请输入你要加密的内容");
String pass =scan.next();
System.out.println("原字符串的内容" +pass);
String secrerult=secret(pass,secret);
System.out.println("加密后的内容"+secrerult);
String uncrypresult = secret(secrerult,secret);
System.out.println("解密后的内容"+uncrypresult);
}
public static String secret(String value,char secret)
{
byte[] bt =value.getBytes();//将其转化为字符数组
for(int i=0;i<bt.length;i++)
{
bt[i]=(byte)(bt[i]^(int)secret); //两次位或运算返回
}
String newresult =new String(bt,0,bt.length);
return newresult;
}
}
6. Format bank card number
Write a program to enter the bank card number and display it with every 4 characters plus a space. For example, if the bank card number is 62220630108589564785130 , the output is 6222 0630 1085 8956 4785 130 .
package 作业练习.test3;
import java.util.*;
public class str6 {
public static void main(String[] args) {
System.out.println("请输入你的银行卡号:");
String bank = new Scanner(System.in).next();
char[] id = bank.toCharArray();
String changeid = new String();
for (int i = 0; i < id.length; i++) {
if (i % 4 == 0 && i > 0) {
changeid += ' ';
}
changeid += id[i];
}
System.out.println(changeid);
}
}
7. Write a program, input an English sentence, change the first character of each word to uppercase and then output.
package 作业练习.test3;
import java.util.Scanner;
public class Exer07 {
public static void main(String[]args)
{
System.out.println("输入一个英文句子");
String in =new Scanner(System.in).nextLine();
String [] s=in.split(" ");
String str2 =new String();
for(int i=0;i<s.length;i++)
{
s[i]=s[i].substring(0,1).toUpperCase()+s[i].substring(1);
if(i==s.length-1)
{
str2=str2+s[i];
}else
{
str2=str2+s[i]+' ';
}
}
System.out.println(str2);
}
}
8. Write a program to generate a random phone number. The first five digits of the phone number are 15923, and the last six digits are randomly generated.
package 作业练习.test3;
import java.util.Random;
public class Exer08 {
public static void main(String[] args)
{
String firtst_five = "15923";
String lastsix =new String();
String Phone =new String();
Random rnd =new Random();
for(int i=0;i<6;i++)
{
int nmber =rnd.nextInt(10);
lastsix += nmber;
}
Phone =firtst_five+lastsix;
System.out.println(Phone);
}
}
9. Write a program to randomly generate a 4-digit verification code, which can contain the size and numbers of English characters.
package 作业练习.test3;
import java.util.Random;
class Random_1 {
public String string() {
String ZiMu = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGJKLZXCVBNM1234567890";
String result = "";
Random random = new Random();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(ZiMu.length());
char c = ZiMu.charAt(index);
result += c;
}
return result;
}
public static void main(String[] args) {
Random_1 test2 = new Random_1();
System.out.println(test2.string());
}
}
10. Using object-oriented programming ideas, store the student information in Table 1 in the List collection (ArrayList or LinkedList). Write a program to achieve the following functions:
Table 1 Student Information
student ID |
Name |
date of birth |
201644001 |
Zhang San |
February 3, 1997 |
201644002 |
Li Si |
November 11, 1998 |
201644003 |
Wang Wu |
March 2, 1996 |
201644004 |
Zhao Liu |
December 12, 1996 |
201644005 |
Zhou Zheng |
October 10, 1997 |
(1) Create a Student student class. The class includes three member variables, which are student ID, name, and date of birth. Add a construction method without parameters, add a construction method with the above three parameters, and add Getters for each member variable. And Setter method, rewrite the toString() method (return string format: student ID name, date of birth)
(2) Add the students in Table 1 to the List in turn;
(3) Output all student information (using Iterator);
(4) A student (student ID: 201644006, name: Li Ming, date of birth: January 12, 1998) enrolled midway, and added it to the List collection;
(5) A student "Wang Wu" dropped out of school halfway and deleted it from the List collection;
(6) Traverse and output all student information again (using the foreach statement).
(7) Output the student ID, name and date of birth of the youngest student (consider the case where there is more than one student with the youngest age
package 作业练习.test3;
import java.util.*;
public class Students {
public String id;//学号
public String name;//姓名
public String birth;//出生日期
Students(){} //不带参数的构造方法
Students(String id, String name, String birth) //带三个参数的构造方法
{
this.id = id;
this.name = name;
this.birth = birth;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public static void addStudent(List<Students> list) //增加学生信息
{
Scanner sc = new Scanner(System.in);
boolean flag = false;
String newStudentid;
while (true) {
System.out.println("请输入学号:");
newStudentid = sc.nextLine();
for (int i = 0; i < list.size(); i++) {
Students s = list.get(i);
if (s.getId().equals(newStudentid)) {
flag = true;
break;
}
}
if (flag == true) {
System.out.println("输入的学生已存在,请重新输入");
} else {
break;
}
}
System.out.println("请输入学生的姓名");
String newStudentname = sc.nextLine();
System.out.println("请输入学生的生日");
String newStudentbirth = sc.nextLine();
Students newStudent = new Students();
newStudent.setId(newStudentid);
newStudent.setBirth(newStudentbirth);
newStudent.setName(newStudentname);
list.add(newStudent);
}
public static void print1(List<Students> list) //迭代器Iterator输入所以学生信息
{
Iterator<Students> it = list.iterator();
while (it.hasNext()) {
Students st = it.next();
System.out.println("学号: " + st.id + "姓名: " + st.name + "生日: " + st.birth);
}
}
public static void print2(List<Students> list)//用foreach方法输出学生信息
{
for (Students obj : list) {
Students st = obj;
System.out.println("学号: " + st.id + "姓名: " + st.name + "生日: " + st.birth);
}
}
public static void remove(List<Students> list) {
System.out.println("请输入你要移除的学生的姓名");
String movename = new Scanner(System.in).nextLine();
int index = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(movename)) {
index = i;
}
}
list.remove(index);
}
public static void main(String[] args) {
List<Students> list = new ArrayList<Students>();
while (true) {
System.out.println("-----------欢迎进入学生信息管理系统-----------");
System.out.println("请选择相关选项对学生信息进行管理...\n");
System.out.println("1.查看所有学生信息");
System.out.println("2.添加学生信息");
System.out.println("3.删除学生信息");
System.out.println("4.退出系统\n");
Scanner sc = new Scanner(System.in);
// 接收选项数据
System.out.println("请输入你的选项:");
String option = sc.nextLine();
switch (option) {
case "1":
print2(list);
break;
case "2":
addStudent(list);
break;
case "3":
remove(list);
break;
case "4":
System.out.println("退出系统成功!");
System.exit(0);
break;
default:
System.out.println("\n输入错误,请重新选择!\n");
break;
}
}
}
}
11. Programming to simulate user registration function
Requirements: Use the Set collection to store user information (including user name, nickname, and password) to realize the user registration function. If the user name already exists, it cannot be registered. If the user registration succeeds or fails, please output the corresponding prompt message. Note: User names are not case sensitive.
Assume that the following user information already exists:
username |
password |
Tim |
112233 |
Barton |
123456 |
Mary |
654321 |
package 作业练习.test3;
import java.util.HashSet;
import java.util.Iterator;
class Exer09 {
private String userName;
private String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "userName: " + getUserName() + " passWord: " + getPassWord();
}
}
class Set {
public static void main(String[] args) {
// 添加初始信息
Exer09 user1 = new Exer09();
user1.setUserName("Tim");
user1.setPassWord("112233");
Exer09 user2 = new Exer09();
user2.setUserName("Barton");
user2.setPassWord("123456");
Exer09 user3 = new Exer09();
user3.setUserName("Mary");
user3.setPassWord("654321");
// 创建hash对象
HashSet<Exer09> user = new HashSet<Exer09>();
user.add(user1);
user.add(user2);
user.add(user3);
// 输出
Iterator<Exer09> hashIter = user.iterator();
while (hashIter.hasNext()) System.out.println(hashIter.next());
// 新用户
Exer09 newUser = new Exer09();
newUser.setUserName("tim");
newUser.setPassWord("112273");
System.out.println("新的信息:" + newUser.toString());
// 测试
if (!user.add(newUser)) System.out.println("已经注册");
else System.out.println("注册成功");
// 二次迭代
hashIter = user.iterator();
while (hashIter.hasNext()) System.out.println(hashIter.next());
}
}
12. Use Map to store user names and passwords. Please change the password for one of the users. Please output all accounts and their corresponding passwords.
At least 4 users or more are required.
1. Please use Map to create a "professional-college" correspondence table based on the information provided in Table 2, and realize programming: when the user enters the professional name, output the name of the college to which it belongs. Requirement: Allow users to enter a profession with leading or trailing spaces.
Table 3-2 Comparison table of colleges and majors
Academy name |
profession |
Information Institute |
computer science and Technology |
Internet of Things Engineering |
|
Software engineering |
|
Electric Automation |
|
School of Law, Politics and Economics |
international economy and trading |
social work |
|
Resource and Environmental Economics |
|
Petroleum Engineering College |
Oil drilling technology |
Oil and gas extraction technology |
|
Oil and gas geological exploration technology |
|
Oil and gas storage and transportation technology |
package 作业练习.test3;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Map2 {
public static void main(String[] args) {
Map<String, String> hm = new HashMap<String, String>();
hm.put("计算机科学与技术","智能技术与工程");
hm.put("物联网工程","智能技术与工程");
hm.put("软件工程","智能技术与工程");
hm.put("智能科学与技术","智能技术与工程");
hm.put("物流管理","工商管理");
hm.put("酒店管理", "工商管理");
hm.put("人力资源管理", "工商管理");
hm.put("英语", "外国语");
hm.put("西班牙语", "外国语");
Scanner reader = new Scanner(System.in);
String key = reader.nextLine();
String key2 = reader.nextLine();
String nkey = key.trim(); //去掉字符串两端的多余的空格
String nkey2 = key2.trim();
hm.put(nkey,nkey2);
//map输出方法;
System.out.println(hm);
hm.clear();
}
}
One word per text
Want to cross the distance to hug you rather than holding your phone and saying miss you.
The lucky color in this article is tender green! I hope you can all survive every distance! ~!