我正在编写这个简单的程序,并且在数据验证部分,程序必须拒绝用户输入,如果它包含一个数字,使用ASCII,但使用(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
似乎不工作
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;
public class Liu_YiJun_A2Q4 {
public static void main(String[] args) {
String fName = "", lName = "", type = "", add = "", post = "", use = "c", use2 = "";
int age = 0, phone = 0, numOfU = 0;
char ch = 0;
while (use.equalsIgnoreCase("c")) {
System.out.println(numOfU);
Scanner input = new Scanner(System.in);
System.out.print("Please enter your FIRST name: ");
fName = input.nextLine();
while (fName.length() >= 15 && (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("The characters in the name are too long OR The value is not a letter");
System.out.print("Please enter your FIRST name: ");
fName = input.nextLine();
}
System.out.print("Please enter your LAST name: ");
lName = input.nextLine();
System.out.print("Please enter your AGE: ");
age = input.nextInt();
input.nextLine();
System.out.print("Please either FT ot PT: ");
type = input.nextLine();
System.out.print("Please enter the ADDRESS: ");
add = input.nextLine();
System.out.print("Please enter the POSTAL CODE: ");
post = input.next();
System.out.print("Please enter your PHONE NUMBER: ");
phone = input.nextInt();
System.out.println();
System.out.println("*********************************************");
String val = "" + ((int) (Math.random() * 9000) + 1000);
System.out.println("Membership ID: " + val);
System.out.println("Name of new member: " + fName + " " + lName);
System.out.println("Age: " + age);
System.out.println("User is: " + type);
System.out.println("Address: " + add + " " + post);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
System.out.println("Member Since: " + sdf.format(cal.getTime()));
System.out.println();
System.out.print("Enter (C) to enter a new user or X to Exit: ");
use = input.next();
if (use.equals("x")) {
System.out.println("Thanks for using ICMSG Membership System. You have entered " + numOfU + " users in this session. Have a nice day!");
}
}
}
}
答案 0 :(得分:0)
由于学习目的,我不会直接回答,但是你应该如何做到这一点:
test1 = x
然后你会知道,如果给定的字母是字母。 正如@VGR在评论中指出的那样,这不是Regex的任务。
另外,将 final String alphabet = "abcdefghijklmnoprstuwxyz"; // define allowed chars
char inputChar = 'c'; // get the input from scanner or whatever
boolean allowed = alphabet.toUpperCase().contains(Character.toUpperCase(inputChar) + "");
变量作为类成员来阻止循环中的常量内存分配。
答案 1 :(得分:0)
您检查过字符ch
是否为ASCII字母。
但是,您必须检查输入中的每个字符都是一个字母。
读取输入后。
要做到这一点,你需要遍历字符串fName
中的所有字符,依此类推。
for (int i = 0; i < fName.length(); ++i) {
char ch = fName.charAt(i);
if (is not a letter) {
break; // Error, jump out of the for-loop.
}
}
fName
和所有其他输入。
如果仍未处理for循环,请使用while循环。
int i = 0;
while (i < fName.length()) {
...
++i;
}