gpt4 book ai didi

java - 验证扫描仪仅允许字符

转载 作者:行者123 更新时间:2023-12-01 23:22:13 25 4
gpt4 key购买 nike

这是我的第一个问题。我正在参加在线编码类(class),它的说明中肯定存在一些漏洞。我们的任务是获取 2 个仅包含一个字符的不同输入,并将它们转换为 ASCII 值。我很沮丧,我正在努力解决如何验证输入仅允许一个字符,而不是数字或符号等内容,然后在出现此类错误时退出程序。这是我的代码。

import java.io.*;
import java.util.*;
public class AndrewBrutonMod4TopSecret
{
public static void main(String args[])
{
Scanner kaReader = new Scanner(System.in);
System.out.println("Enter the first initial of your first name:");
String i1 = kaReader.next();
System.out.println("Enter the first initial of your last name:");
String i2 = kaReader.next();
char a = i1.charAt(0);
char b = i2.charAt(0);
char a1 = Character.toUpperCase(a);
char b1 = Character.toUpperCase(b);
int c = (int)a;
int d = (int)b;
System.out.println("Initials: "+a1+" "+b1);
System.out.println("Encrypted Initials: "+c+" "+d);
}
}

有什么想法吗?

最佳答案

I'm struggling with how I'm supposed to validate the inputs to only allow one character, and not something such as a number or symbol

您可以使用 isAlphabetic() 方法

Java 文档:

Determines if the specified character (Unicode code point) is an alphabet. A character is considered to be alphabetic if its general category type, provided by getType(codePoint), is any of the following:

UPPERCASE_LETTER

LOWERCASE_LETTER

TITLECASE_LETTER

MODIFIER_LETTER

OTHER_LETTER

LETTER_NUMBER

or it has contributory property Other_Alphabetic as defined by the Unicode Standard.

private static boolean isValidChar(char ch) {
return Character.isAlphabetic(ch);
}

and then exit the program if such an error arises

例如

if (!isValidChar(a))
System.exit(-1);

关于java - 验证扫描仪仅允许字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58325397/

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