问题:在数组中打印索引、索引值、长度索引有循环


import java.util.Scanner;
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");

Scanner input = new Scanner(System.in);
String word = input.nextLine();

String[] parts = word.split(" "); 
String max = parts[0]; 
int max_box; int parts_L = parts.length; 
int max_L; int i;

for (i = 1; i < parts_L; i++) {
if (parts[i].length() > max.length()) { 
max = parts[i];
max_box = i;
max_L = parts[i].length();
}
}
/* the problem occurs in the next line where it does not print the max value, 
and it considers max_L without a value which I did give it a value in the 
loop and the I value should be the same as the index of the longest 
string but it gives me the last index in the array */ 

System.out.print("The longest word is " + max + " contain " + 
max_L + " letters, in box " + i);
input.close();
}
}

问题是您将imax_box混合。以下内容应该如您所期望的那样工作:

public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String longestWord = parts[0];
int longestWordSize = longestWord.length();
int longestWordLocation = 0;
for (int i = 1; i < parts.length; i++) {
if (parts[i].length() > longestWordSize) {
longestWord = parts[i];
longestWordLocation = i;
longestWordSize = longestWord.length();
}
}
System.out.print("The longest word is " + longestWord + " contain " +
longestWordSize + " letters, in box " + longestWordLocation);
input.close();
}
}

此外,在命名变量时要尽量明确,max_Lmax_box不是很好的名称,因为它们很难理解。

最新更新