简体   繁体   English

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

[英]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(); } }

The problem is that you are mixing i with max_box .问题是您将imax_box混合在一起。 The following should work as you expect:以下应该按您的预期工作:

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_size = max.length();
        int max_location = 0;

        for (int i = 1; i < parts.length; i++) {
            if (parts[i].length() > max_size) {
                max = parts[i];
                max_location = i;
                max_size = max.length();
            }
        }

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

Additionally, try to be explicit when naming your variables, max_L and max_box are not very good names because they are hard to understand.此外,在命名变量时尽量明确, max_Lmax_box不是很好的名称,因为它们很难理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM