java - 在数组列表中搜索最大的数字

标签 java arraylist

所以我现在正在编写一个代码来搜索数组列表并打印出最大的一个。此代码提示用户输入 BankAccount 名称以及该帐户有多少钱。目前我遇到了不知道如何在数组列表中搜索最大数字的问题。我也不知道如何将每个余额与 maxBalance 进行比较。感谢任何帮助,谢谢。

        import java.io.*;
        import java.util.*;
        import java.text.*; 

        public class Project43Tester
        {
            public static void main(String args[])
            {
                NumberFormat formatter = NumberFormat.getNumberInstance( );
                formatter.setMinimumFractionDigits(2);
                formatter.setMaximumFractionDigits(2);
                String name;
                ArrayList <String> aryLst = new ArrayList<String>();

                do
                {
                    Scanner kbReader = new Scanner(System.in);
                    System.out.print("Please enter the name to whom the account belongs.(\"Exit\" to abort)");
                    name = kbReader.nextLine( );
                    if( !name.equalsIgnoreCase("EXIT") )
                    {
                        System.out.print("Please enter the amount of the deposit. ");
                        double amount = kbReader.nextDouble();
                        System.out.println(" ");
                        ArrayList <String> BankAccount = new <String> ArrayList();
                        AryLst.add(BankAccount);
                    }
                }while(!name.equalsIgnoreCase("EXIT"));

        Search aryList and print out the name and amount of the largest bank account

                BankAccount ba = //get first account in the list
                    double maxBalance = ba.balance;
                String maxName = ba.name;

                for(int j = 1; j < aryLst.size( ); j++)
                {
                    ?
                    ? Step through the remaining objects and decide which one has
                    largest balance (compare each balance to maxBalance)
                    ?
                }

                System.out.println(" ");
                System.out.println("The account with the largest balance belongs to " + maxName + ".");
                System.out.println("The amount that the account contains is $" + formatter.format(maxBalance) + ".");
            }
        }

最佳答案

您将必须遍历 ArrayList。在遍历ArrayList的过程中,将第一个元素设置为max,并与next进行比较。如果更大,则将新元素设置为最大值。

关于java - 在数组列表中搜索最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21847606/

相关文章:

java - 获取两个 arrayList 之间的差异,但以大写形式比较它们

随着时间的推移,Java 访问数组列表中的元素会变慢

java - java顺序搜索的辅助方法

java - 如何访问 Java 中 Arraylist 中的字典数据?

java - 使用AlwaysUseFullPath 属性了解使用DispatcherServlet 的URL 映射

java - 是否可以使用java更改谷歌云存储文件的文件名?

java - 为每个应用程序创建的每个jvm,这是一个线程还是一个进程

Java内存堆错误

java - JUnit:测试异常不起作用(AssertionError:即使抛出异常,也是预期的异常)

java - 如何在JSP中创建对象的数组列表