三行代码  ›  专栏  ›  技术社区  ›  Noble.Programmer

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

  •  0
  • Noble.Programmer  · 技术社区  · 1 月前
    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();
        }
    }
    
    1 回复  |  直到 1 月前
        1
  •  0
  •   João Dias    1 月前

    问题是你在混合 i 具有 max_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_L