簡體   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(); } }

問題是您將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 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();
    }
}

此外,在命名變量時盡量明確, max_Lmax_box不是很好的名稱,因為它們很難理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM