枚举中的等间距? [英] Equal spacing in Enumerations?

查看:139
本文介绍了枚举中的等间距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个Java课程,该部分是枚举。我在我的枚举中有这个:

  public enum tuna {
Camaro(Orange,1968),
Silverado(Red,1996),
Sierra(Black,2007),
Equinox(Silver,2011);

private final String color;
private final String year;


金枪鱼(String carColor,String age){
color = carColor;
年=年龄;

}
public String getColor(){
return color;
}

public String getYear(){
return year;
}
}

这在我的Java类中打印出来:

  for(金枪鱼车:tuna.values()){
System.out.printf(%s\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, >

哪个打印出来:





看看Silverado的Red和1996如何在右边(因为Silverado比其他单词更长吗?
那么我怎么可以解决它,所以长的单词的细节与其他单词的间隔相同?



如果我缩短Silverado到Silver,这是正常的:



解决方案

我建议不要使用标签,而是使用字符串格式化,即使用 System.out.format(...)并计算长度h通过获取最长名称的长度。



示例:

  //这是一个捷径,你必须计算max 
int maxlength = tuna.Silverado.name()。length();

(tuna t:tuna.values()){
System.out.format(% - + maxlength +s%-10s%4s\\\
,t .name(),t.getColor(),t.getYear());
}

输出:

  Camaro Orange 1968 
Silverado Red 1996
Sierra Black 2007
Equinox Silver 2011


I was working on a Java lesson and the section was on Enumerations. I have this in my Enum:

public enum tuna {
 Camaro("Orange", "1968"),
 Silverado("Red","1996"),
 Sierra("Black","2007"),
 Equinox("Silver","2011");

  private final String color;
  private final String year;


tuna(String carColor, String age){
    color = carColor;
    year = age;

 }
public String getColor(){
    return color;
 }

public String getYear(){
    return year;
 }
}

and this in my Java Class that prints it out:

for(tuna cars: tuna.values()){
    System.out.printf("%s\t\t%s\t\t%s\n", cars, cars.getColor(), cars.getYear()

Which prints out:

See how the "Red" and "1996" for the Silverado are way over on the right (because "Silverado" is longer than the other words)? Well how can I fix it so the details for long words are equally spaced as the rest?

P.S. if I shorten "Silverado" to "Silver", it's normal:

解决方案

I'd suggest not using tabs but string formatting, i.e. use System.out.format(...) and calculate the length of each format specifier by getting the length of the longest name. Then build the format string dynamically.

Example:

//that's a shortcut, you'd have to calculate the max
int maxlength = tuna.Silverado.name().length();

for( tuna t : tuna.values() ) {
  System.out.format( "%-" + maxlength + "s   %-10s %4s\n", t.name(), t.getColor(), t.getYear() );
}

Output:

Camaro      Orange     1968
Silverado   Red        1996
Sierra      Black      2007
Equinox     Silver     2011

这篇关于枚举中的等间距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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