我是编程和Java的新手。我遇到的问题是我的程序只识别大写字母,如果用户输入是非字母字符则显示错误信息。我被指示使用布尔和字符串来解决这个问题。 谢谢!
Scanner in = new Scanner(System.in);
System.out.println("Enter a single letter, and I will tell you what the corresponding digit is on the telephone:");
String letter = in.nextLine();
String upperCase = letter.toUpperCase();
boolean letter = letter.hasUpperCase();
if (letter.equals("A") || letter.equals("B") || letter.equals("C")){
System.out.println("The digit 2 corresponds to the letter " + letter + " on the telephone.");
}
else if{
System.out.println("Please enter a letter.")
}
答案 0 :(得分:1)
如果你只想检查大写字母,那么一种方法是检查每个字符的ASCII值,看它是否在65到90之间。如果字符串中的所有字符符合这个标准,那么你有一个字符串仅包含AZ。如果没有,您可以根据需要显示错误消息。请根据您的代码查看以下示例。
Scanner in = new Scanner(System.in);
System.out.println("Your message here");
String userInput = in.nextLine();
in.close();
// Here you don't know what they entered
// but looking at your code, you want
// only ONE uppercase character
// validate the input
boolean validInput = false;
if (userInput.length() == 1) {
char letter = userInput.charAt(0);
if (letter >= 65 && letter <= 90) {
validInput = true;
}
}
// handle accordingly
if (validInput) {
// your logic here
} else {
System.out.println("Your error message");
}
编辑 - 如何检查字符是数字还是符号
...
// Here you don't know what they entered
// the validation / execution changes based on your needs
// suggestion: define other methods
if (userInput.length() == 1) {
char c = userInput.charAt(0);
// what kind of character is it?
if (isUppercaseLetter(c)) {
// do something with the uppercase letter
} else if (isDigit(c)) {
// do something with the digit
} else if (isSymbol(c)) {
// do something with the symbol
} else {
// whatever else it might be, this could be an error message
}
}
...
// methods here
private boolean isUppercaseLetter(char c) {
return (c >= 'A' && c <= 'Z'); // ascii codes 65 to 90
}
private boolean isDigit(char c) {
return (c >= '0' && c <= '9'); // ascii codes 30 to 39
}
private boolean isSymbol(char c) {
return (c >= '!' && c <= '/'); // 21 to 47, modify based on acceptable symbols
}
答案 1 :(得分:0)
我不确定你的要求。但是我修改了你的代码,所以它可以根据我看待它的方式运行。
Scanner in = new Scanner(System.in);
System.out.println("Enter a single letter, and I will tell you what the corresponding digit is on the telephone:");
String letter = in.nextLine();
boolean hasUpper = false;
if (letter.equals("A") || letter.equals("B") || letter.equals("C")){
hasUpper = true;
System.out.println("The digit 2 corresponds to the letter " + letter + " on the telephone.");
}
else if(letter.equals("a") || letter.equals("b") || letter.equals("c")){
System.out.println("Error! The letter has to be uppercase.");
}
else{
System.out.println("Please enter a letter.");
}