Java - 如何设置字符串的长度 [英] Java - how do I set a length of a string

查看:1582
本文介绍了Java - 如何设置字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的String设置一个长度,因为我希望我的ArrayList的不同元素(由JList显示)正确对齐。



这里是问题的图像: https://prnt.sc/k7vg91



我尝试了什么:



我尝试使用while循环,但JList中的元素没有正确排列。

nameBoisson是我正在使用的字符串。



 public String toString()
{
while(nameBoisson.length()< 49)
{
nameBoisson = nameBoisson +;
}
返回nameBoisson + prixDeVente +€+ conditionnement +L;
}

解决方案

你必须使用固定宽度的字体( Monospaced字体 - 维基百科 [ ^ ])像 Courier 一样显示正确对齐的文本表。如何选择这样取决于使用的输出方法。



这使用固定宽度字体:

商品价格
AnItem€13.49
另外€127.80

使用比例字体相同:

项目价格
AnItem€13.49
另一个€127.80





被忽视 JList

设置字体使用类似

 myList.setFont( new 字体(Font.MONOSPACED,Font.PLAIN, 12 )); 

要格式化行字符串,请使用 String.format 按解决方案1中的建议:

 字符串 strLine = 字符串 .format( % -  49s%10.2f€,nameBoisson,prixDevente); 

这里% - 49s 打印一个与尾随空格对齐的字符串,最多总长度为49个字符且%10.2f 打印一个浮点值,右对齐,总长度为10个字符,小数点后2位,正值为前导空格。

[/ EDIT]


您可以使用 String.format 来查看,例如: Java String.format examples [ ^ ]。

I want to set a length to my String, as I want the different elements of my ArrayList, displayed by a JList, to be aligned correctly.

Here is an image of the problem: https://prnt.sc/k7vg91

What I have tried:

I tried using this while loop, but the element in the JList are not lining up properly.
nameBoisson is the String I'm using.

public String toString()
    {
        while (nameBoisson.length() <49)
        {
            nameBoisson = nameBoisson + " ";
        }
        return nameBoisson +prixDeVente +" € " +conditionnement +"L";
    }

解决方案

You have to use a fixed width font (Monospaced font - Wikipedia[^]) like Courier to show properly aligned text tables. How to select such depends on the used output method.

This uses a fixed width font:

Item     Price
AnItem   €    13.49
Another  €   127.80

The same using a proportional font:

Item     Price
AnItem   €    13.49
Another  €   127.80


[EDIT]
Overlooked the JList.
To set the font use something like

myList.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

To format the line strings use String.format as suggested in solution 1:

String strLine = String.format("%-49s% 10.2f € ", nameBoisson, prixDevente);

Here %-49s prints a string left aligned with trailing spaces up to a total length of 49 characters and % 10.2f prints a floating point value right aligned with a total length of 10 characters, 2 digits after the decimal point, and a leading space for positive values.
[/EDIT]


You may use String.format for the purpose, see, for instance: Java String.format examples[^].


这篇关于Java - 如何设置字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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