【发布时间】:2020-04-12 20:44:31
【问题描述】:
我是 Java 初学者,遇到了这个学校问题:
XYZ 门控小区的权限要其居民姓名数据应按以下格式存储-居民姓名他/她父亲的姓名。编写一个程序,将父亲的名字与居民的名字连接起来。名称应经过验证,验证时名称应仅包含字母且允许空格。如果名称无效,则显示消息“Invalid name”。如果是有效字符串,则将其转换为大写并打印出来
Sample Input 1:
Inmate's name:Aron
Inmate's father's name:Terby
Sample Output 1:
ARON TERBY
错误:每当我输入两个字母的囚犯名字时,它都会打印出“无效输入”,例如 Aron Kumar,否则对于单个单词字符串输入代码可以正常工作。
这是我写的代码:
Scanner sc=new Scanner(System.in);
System.out.println("Inmate's name:"); //if I enter 2 word string,output-"Invalid name1"//
String name=sc.nextLine();
System.out.println("Inmate's father's name:");
String fname=sc.nextLine();
String s3=name.toUpperCase();
String s4=fname.toUpperCase();
char[] a1= s3.toCharArray();
char[] a2= s4.toCharArray();
for(int i=0;i<a1.length;i++)
{
if(a1[i]>='A' && a1[i]<='Z')
count=1;
else {
System.out.print("Invalid name1");
count=0;
break; }
}
if(count==1)
{
for(int i=0;i<a2.length;i++)
{
if(a2[i]>='A' && a2[i]<='Z')
count=2;
else {
System.out.print("Invalid name");
break; }
}
}
if(count==2) {
System.out.print(s3+" "+s4);
}
}
}
【问题讨论】:
-
如果您发布了一个不带行号的minimal reproducible example 会更好,因为它们会阻止任何人复制和运行您的代码。
-
感谢您的宝贵建议,先生。我是这个平台的初学者,下次我会记住这一点。