第2章课后作业

第4题  从控制台输入字符串,长度必须是6,如果输入的字符串长度不等于6,则重新输入.

public class Test5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入长度为6的字符串:");
String str = in.nextLine();
while (str.length() != 6) {
System.out.println("请输入长度为6的字符串:");
str = in.nextLine();
}
if (str.length() == 6) {
System.out.println("程序退出,你输入了:"+str);
}
}

}

第5题  对录入的信息进行有效性验证.

import java.util.Scanner;
public class Test {
static Scanner in = new Scanner(System.in);
static String birthday;
static String password;
/*
* 生日格式判断
*/
public static void judge() {
System.out.print("请输入会员生日<月/日:00/00>:");
birthday = in.next();
int cont = 0;
int cont1 = 0;
for (int i = 0; i < birthday.length(); i++) {
char c = birthday.charAt(i);
if (c < '0' || c > '9') {
cont++;
}
if(c=='/') {
cont1++;
}
}
if (cont > 1||cont1>1||cont1<=0) {
System.out.println("生日形式错误!\n");
judge();
}
String[] a = new String[2];
a = birthday.split("/");
int a1 = Integer.parseInt(a[0]);
int a2 = Integer.parseInt(a[1]);
if (a1 > 12 || a1 <= 0 || a2 <= 0 || a2 > 31) {
System.out.println("生日形式错误!\n");
judge();
}
}
/*
* 密码判断
*/
public static void passwordJudge() {
System.out.println("请输入会员密码(6~10位)");
password = in.next();
if (password.length() < 6 || password.length() > 10) {
System.out.println("密码形式错误!\n");
passwordJudge();
}
}
public static void main(String[] args) {
judge();
System.out.println("该会员的生日是:" + birthday);
passwordJudge();
System.out.println("该会员的密码是:" + password);
}
}

第6题  创建会员编号,会员编号为4位随机数字,创建完成后显示会员信息

import java.util.Scanner;


public class Test7 {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入会员姓名:");
String name = in.next();
System.out.println("请输入会员性别:");
String sex = in.next();
System.out.println("请输入会员年龄:");
int age = in.nextInt();
String vipNo = "";
for (int i = 0; i < 4; i++) {
int num = (int) (Math.random() * 10);
vipNo += num;
}
System.out.println("创建会员成功:\n会员编号:" + vipNo + "\n会员详细信息:\n" + name + " " + sex + " " + age);
}
}

猜你喜欢

转载自blog.csdn.net/weixin_41880408/article/details/80314074