问题:打印一个索引,索引的值,数组中的长度索引有一个循环

Problem: printing an index, value of index, length index in an array has a loop

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 不是很好的名字,因为它们很难理解。