使用 toString 方法在不带括号和逗号的数组列表中显示信息 [英] using the toString method to display information in an arraylist without brackets and commas

查看:58
本文介绍了使用 toString 方法在不带括号和逗号的数组列表中显示信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 toString 方法在数组列表中显示数据.我如何编写代码,以便在我的信息周围没有 [ , , ] 的情况下显示信息

I am using a toString method to display data in an arraylist. How do I write the code so that it displays the information without the [ , , ] around my information

请看下面的代码:

case 6:
            System.out.println("Enter an account number to view the transactions of the account");
            number=keyboard.nextLong();
            found=false;
            try{
                for(int i=0;i<aBank.getAccounts().size();i++){

                if(aBank.getAccounts().get(i).getAccountNumber().compareTo(number)==0){
                    found=true;
                    System.out.println("Account " + number + ":\tStart Balance: " +money.format(aBank.getAccounts().get(i).getStartBalance()));
                    System.out.println(aBank.getAccounts().get(i).getTransaction().toString());
                    System.out.println("Ending Balance :" +money.format(aBank.getAccounts().get(i).getBalance()));
                }
                }
            }

        catch (Exception e){
            System.out.println("Unable to process request.\n" +e.getMessage());
        }
            break;

这是输出:

Account 1:  Start Balance: $1000.00
[Deposit    1   6/6/2011    $500.00
, Deposit   2   6/6/2011    $489.00
, Deposit   3   6/6/2011    $262.00
, Withdrawal    4   6/6/2011    $897.00
, Withdrawal    5   6/6/2011    $56.32
, Withdrawal    6   6/6/2011    $78.24
]
Ending Balance :$1219.44

注意需要去掉的括号和逗号

notice the brackets and commas that need to be removed

推荐答案

根本不要使用 toString().它不打算用于创建格式化的 UI 字符串.它是一个开发者工具,而不是一个用户展示工具.

Don't use toString() at all. It is not meant to be used to create formatted UI strings. It is a developer tool, not a user presentation tool.

对于对象表示具有可用于这两个目的的简单可接受格式的内容的情况,我将添加一个警告.Java 原始包装器(如 Integer 和 Float)就是一个例子.其他简单的类(例如 2D 点)也可以在这方面发挥作用,但随着对象变得更加复杂,这种方法很快就会崩溃.

I will add a caveat for the cases where the object represents something with a simple accepted format that can serve both purposes. Java primitive wrappers (like Integer and Float) are an example of this. Other simple classes such as a 2D point can work in this regard as well, but this quickly falls apart as an object becomes more complex.

要执行您正在尝试的操作,只需创建一个方法来进行显示并在该方法中进行格式化.

To do what you are attempting, just create a method to do your display and do the formatting in that method instead.

这篇关于使用 toString 方法在不带括号和逗号的数组列表中显示信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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