gpt4 book ai didi

java - 如何控制用户在输入提示中输入多少个字母和数字?

转载 作者:行者123 更新时间:2023-11-30 10:33:57 25 4
gpt4 key购买 nike

我是编程新手,我们接到了第一份作业!我的整个代码运行良好,但这是我的问题:

我们必须提示用户输入由 2 个字母和 3 位数字组成的帐户 ID。

到目前为止我只有一个基本的输入/输出提示

//variables

String myID;

//inputs

System.out.println("Enter your ID:");
myID = input.nextLine();

所以它所做的就是让用户以任意顺序和长度输入他们想要的字母和数字的数量。我更不明白如何“控制”用户的输入。

最佳答案

正如您所说您不知道 regex ,我编写了这段代码以通过 while 循环进行迭代并检查每个字符是字母还是数字。提示用户提供帐号,直到输入有效帐号为止

import java.util.Scanner;

class LinearArray{

public static void main(String args[]){

Scanner input = new Scanner(System.in);
boolean isIdValid = false;
String myId;

do{
System.out.println("account ID that consists of 2 letters followed by 3 digits");
myId = input.nextLine();
//Check if the length is 5
if (myId.length() == 5) {
//Check first two letters are character and next three are digits
if(Character.isAlphabetic(myId.charAt(0))
&& Character.isAlphabetic(myId.charAt(1))
&& Character.isDigit(myId.charAt(2))
&& Character.isDigit(myId.charAt(3))
&& Character.isDigit(myId.charAt(4))) {
isIdValid = true;
}
}
}while(!isIdValid);
}
}

关于java - 如何控制用户在输入提示中输入多少个字母和数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41930987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com