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

Time:11-29

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

CodePudding user response:

The problem is that you are mixing i with max_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 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();
    }
}

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.

  • Related