问题描述
我的项目是要求用户介绍最多10个全名(最多120个字符)和至少两个全名(至少4个字符)。如果用户至少达到5个有效名称,可以引入结束来结束程序,我该怎么办? (注意:如果程序有10个名称,则需要结束。)
My project is to ask the user to introduce up to 10 full names with up to 120 characters and at least two names with at least 4 characters. If the user reaches at least 5 valid names could introduce "end" to end the program, how do I would do it? (Note: The program needs to end if it reaches 10 names.)
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter up to 10 full names with up to 120 characters and at least two names with at least 4 characters:");
String fullName;
String[] SeparatedName;
int i = 0;
do {
fullName= keyboard.nextLine();
i++;
SeparatedName= fullName.split(" ");
//System.out.println(Arrays.toString(SeparatedName));
int l = 0;
for(int n = 0; n < SeparatedName.length; n++){
if(SeparatedName[n].length() >= 4 ) {
l++;
}
}
if(l >= 2 && fullName.length() <= 120 || fullName.equalsIgnoreCase("end") ) {
//valid name
System.out.println("'" +fullName+ "'" + " is valid");
}
else {System.out.println("'" +fullName+ "'" + " is invalid");}
}
while(!fullName.equalsIgnoreCase("end") || i<10);
keyboard.close();
}
输出(不结束):
aaaa aaaa
'aaaa aaaa' is valid
aaa aa
'aaa aa' is invalid
aaaa aaaa
'aaaa aaaa' is valid
aaaa aaaa
'aaaa aaaa' is valid
aaaaaaa aaaaaa
'aaaaaaa aaaaaa' is valid
end
'end' is valid
当用户介绍end时应停止,因为它已经有5个有效名称。如果达到10个全名,应该停止,但不会停止。
When the user introduced end should stop because it has already 5 valid names. If it reaches 10 full names should stop and it doesn't.
推荐答案
代替
if(l >= 2 && fullName.length() <= 120 || fullName.equalsIgnoreCase("end") ) {
//valid name
System.out.println("'" +fullName+ "'" + " is valid");
}
else {System.out.println("'" +fullName+ "'" + " is invalid");}
条件在您的代码中,我认为以下 if-elseif-else
条件可以更好地满足您的需求
condition in your code, I think the following if-elseif-else
condition addresses your needs better
if (fullName.equalsIgnoreCase("end")) {
break; // exits the do while loop
} else if (l >= 2 && fullName.length() <= 120 ) {
//valid name
System.out.println("'" +fullName+ "'" + " is valid");
} else {
System.out.println("'" +fullName+ "'" + " is invalid");
}
这篇关于在“扫描”中至少有5个有效名称,并在其中添加“结束”字样结束程序-JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!