在ArrayList中查找最大的字符串 [英] Finding Largest String in ArrayList

查看:150
本文介绍了在ArrayList中查找最大的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//我试图在我的ArrayList中找到最大的String并将其打印出来,并且还包括最大元素所在的索引并将其打印到屏幕上。我只是想知道我哪里出错了。

// Im trying to find the largest String in my ArrayList and print it out and also to include what index the largest element resides at and to print that to screen too. Im just wondering where Im going wrong.

谢谢。

import java.util.Scanner;                  
import java.util.ArrayList;

public class ArraylistString
{
   public static void main(String [] args)
   {
    // Instance of Scanner class
      Scanner keyboardIn = new Scanner(System.in);

   // Declare an array list of Strings
      ArrayList<String> Str = new ArrayList<>();
   // Add names to ArrayList
      Str.add("Jim Bob");
      Str.add("Bobby Jones");
      Str.add("Rob Stiles");
      int largestString = Str.size();
      int index = 0;

   // Use for loop to print out elements from ArrayList
      for(int i = 0; i < Str.size(); i++)
      {  // Test which String is the largest
         if(Str[i].size() > largestString)
         {
            largestString = Str[i].size();
            index = i;
         }

      } 
      // Output largest String and index it was found at
      System.out.println("Index " + index + " "+ Str[index] + " " + "is the largest and is size " + largestString);  

   }

}


推荐答案

请尝试这些代码。在这里,我尝试使用get()来访问正常工作的ArrayList元素。

Please try these code . Here i am trying with get() to access the ArrayList elements, which is working correctly.

import java.util.Scanner;                  
import java.util.ArrayList;

class ArraylistString
{
    public static void main(String args[])
    {
        ArrayList<String> Str = new ArrayList<String>();
        Str.add("Jim Bob");
        Str.add("Bobby Jones");
        Str.add("Rob Stiles");
        int largestString = Str.get(0).length();
        int index = 0;

        for(int i = 0; i < Str.size(); i++)
        {
            if(Str.get(i).length() > largestString)
            {
                largestString = Str.get(i).length();
                                index = i;
            }
        }
        System.out.println("Index " + index + " "+ Str.get(index) + " " + "is the largest and is size " + largestString);  

    }

}

这篇关于在ArrayList中查找最大的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆