第二章实用类习题

本文介绍使用Java实现对用户输入的有效性验证,包括特定格式的字符串验证及会员信息的处理过程。通过循环和条件判断确保输入符合要求,如长度固定的字符串及正确格式的生日等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package page3_49;


import java.util.Scanner;


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

}




package page3_49;


package page3_49;


import java.util.Scanner;


public class Vip {
public static void main(String[] args) {
String bd, pw;         //生日,密码
String[] arr = new String[2];    
int cn1 = 0;               // "/"出现的次数
int cn2 = 0;               // 字符出现的次数
Scanner input = new Scanner(System.in);
System.out.print("请输入会员生日<月/日: 00/00>:");
bd = input.nextLine();
for (int i = 0; i < bd.length(); i++) {  //提取输入生日  “/”与字符的个数
char word = bd.charAt(i);
if (word == '/') {          // 如果“/”出现一次个数增加一次
cn1++;
}
if (word < '0' || word > '9') {  // 如果字符出现一次个数增加一次
cn2++;
}
}
while (cn1 > 1 || cn1 <= 0 || cn2 > 1) {            //“/”不能出现2次并且不能一次也没有 ,字符不能出现2次
System.out.println("生日形式错误!");     //   不满足以上条件就生日形式错误
System.out.print("\n请输入会员<月/日: 00/00>:");
bd = input.nextLine();
for (int i = 0; i < bd.length(); i++) {
char word = bd.charAt(i);
cn1 = 0;
cn2 = 0;
if (word == '/') {
cn1++;
}
if (word < '0' || word > '9') {
cn2++;
}
}
}
arr = bd.split("/");
int num1 = Integer.parseInt(arr[0]);    //    /的前半部分
int num2 = Integer.parseInt(arr[1]);       //    /的后半部分
while (num1 <= 0 || num1 > 12 && num2 <= 0 || num2 > 31) {
System.out.println("生日形式输入错误!");
System.out.print("\n请输入会员<月/日: 00/00>:");
bd = input.nextLine();
}
System.out.println("该会员生日是:" + bd);
System.out.print("\n请输入会员密码<6~10位>:");
pw = input.nextLine();
while (pw.length() > 10 || pw.length() < 6) {
System.out.println("密码形式输入错误!");
System.out.print("\n请输入会员密码<6~10位>:");
pw = input.nextLine();
}
System.out.println("该会员密码是:" + pw);
}


}





package page3_49;


import java.util.Scanner;


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值