![](/img/trans.png)
[英]Method that scans array for most common word length, but sends error message if two different elements have the same length
[英]How to have at least two elements of a array with the same length in Java?
我有一個項目,我需要要求用戶引入至少 5 個有效的全名(直到 10 個全名或者如果用戶引入“fim”)。 每個全名需要至少有 2 個名字,每個名字 4 個字符,並且全名只有在不超過 120 個字符時才有效。 我需要為每個全名創建一個數組,其中元素是作為全名一部分的名稱。 這里我有我的代碼。 我有很多選項在評論中不起作用。 “Nome Inválido”標識無效名稱,“Nome Válido”是有效名稱。
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Introduza até 10 nomes completos com até 120 caracteres e pelo menos dois nomes com pelo menos 4 caracteres: ");
String nome;
int i = 0;
do {
//nomes[i] = keyboard.next();
nome = keyboard.nextLine();
i++;
String[] nomeSeparado = nome.split(" ");
System.out.print(Arrays.toString(nomeSeparado));
int j = nomeSeparado[i].length();
/**
1) for(int k = 0; k < 2; k++) {
if(!(j == 4)) {
System.out.println(" Nome Inválido ");
}
else {
System.out.println(" Nome Válido ");
}
}
2) while( k < 2 ) {
if(!(j == 4)) {
System.out.println(" Nome Inválido ");
}
else {
System.out.println(" Nome Válido ");
}
}
3) if(while(!(nomeSeparado[i].length() == 4)<2)) {
System.out.println(" Nome Inválido ");
}
4) for(i = 0; i < 10 ; i++) {
if( j > 2 && nomeSeparado[i].length() == 4 ) {
System.out.println(" Nome Válido ");
}
else {System.out.println(" Nome Inválido ");}
}
**/
}
while(!nome.equalsIgnoreCase("fim") && i<10);
}
每次用戶輸入名稱時,您將第一個名稱保存為nomeSeparado
的第一個元素,將第二個名稱保存為第二個元素。 您需要做的是檢查第一個和第二個元素的長度,並檢查它們是否符合規則。 這樣的邏輯應該有效:
int lengthOfFirstName = nomeSeparado[0].length();
int lengthOfSecondName = nomeSeparado[1].length();
if (lengthOfFirstName >= 4 && lengthOfSecondName >= 4 && lengthOfFirstName + lengthOfSecondName < 120) {
System.out.println("Valid name");
} else {
System.out.println("Invalid name");
}
你為什么使用數組? 我認為 .length() 可以讓你避免這種情況
導入 java.util.Scanner;
public static void main(String[] args) {
String firstName, surname, fullName;
int fullNameCount;
Scanner input = new Scanner(System.in);
System.out.println("Enter your first name");
firstName = input.nextLine();
System.out.println("Enter your surname");
surname = input.nextLine();
if (firstName.length() <= 4 && surname.length() <=4 ){
System.out.println("Invalid name! Exit");
} else{
fullName = firstName + surname;
fullNameCount = fullName.length();
System.out.println(fullNameCheck(fullNameCount));
char[] fullNameArray = fullName.toCharArray();
}
}
public static String fullNameCheck(int fullNameCount){
if (fullNameCount <= 120){
return "Valid Name";
}
else{
return "Invalid Name";
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.