我遇到了一个练习,我必须根据给定字符串的长度添加一些空格。这是我的代码:
public static void main(String[] args) {
final String[] NAMES = {"Spa reine 25cl","Bru plate 50cl","Bru pét 50cl",
"Pepsi","Spa orange", "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche",
"Jus d'orange Looza", "Cécémel", "Red Bull"};
int[][] stock = {{1,56,200,55},{2,42,200,60},{3,62,200,125},{4,45,200,150},{5,25,200,140},{6,72,200,86},{7,40,200,47},{8,48,200,80},{9,24,150,75},{10,36,200,90},{11,15,100,55},{12,25,80,23}};
for(int i = 0; i<NAMES.length;i++) {
String space1 = placeNumberToRank(NAMES[i], Integer.toString(stock[i][1]), 35);
String space2 = placeNumberToRank(NAMES[i], Integer.toString(stock[i][2]), 40);
String space3 = placeNumberToRank(NAMES[i], Integer.toString(stock[i][3]), 45);
System.out.println(space1);
System.out.println(space2);
System.out.println(space3);
}
}
public static String placeNumberToRank(String originalStr, String numberToPlace, int rank) {
int numberOfSpaces = 0;
numberOfSpaces = rank - originalStr.length() - numberToPlace.length();
return originalStr+" ".repeat(numberOfSpaces)+numberToPlace;
}
}
我需要得到的结果是:(注意最后的数字是对齐的)
Spa reine 25cl 56 200 55
Bru plate 50cl 42 200 60
Bru pét 50cl 62 200 125
Pepsi 45 200 150
Spa orange 25 200 140
Schweppes Tonic 72 200 86
Schweppes Agr 40 200 47
Ice Tea 48 200 80
Ice Tea Pêche 24 150 75
Jus d'orange Looza 36 200 90
Cécémel 15 100 55
Red Bull 25 80 23
我现在的结果是:
Spa reine 25cl 56
Spa reine 25cl 200
Spa reine 25cl 55
Bru plate 50cl 42
Bru plate 50cl 200
Bru plate 50cl 60
Bru pét 50cl 62
Bru pét 50cl 200
Bru pét 50cl 125
Pepsi 45
Pepsi 200
Pepsi 150
Spa orange 25
Spa orange 200
Spa orange 140
Schweppes Tonic 72
Schweppes Tonic 200
Schweppes Tonic 86
Schweppes Agr 40
Schweppes Agr 200
Schweppes Agr 47
Ice Tea 48
Ice Tea 200
Ice Tea 80
Ice Tea Pêche 24
Ice Tea Pêche 150
Ice Tea Pêche 75
Jus d'orange Looza 36
Jus d'orange Looza 200
Jus d'orange Looza 90
Cécémel 15
Cécémel 100
Cécémel 55
Red Bull 25
Red Bull 80
Red Bull 23
练习要求调用该方法3次,它需要返回原始str +空格。有没有一种方法可以"融合"?一切都在一起吗?
您应该像这样使用printf()
而不是println()
。
%-30s
编辑字符串左对齐为30个字符的宽度。%4d
编辑一个右对齐宽4个字符的整数。%n
是操作系统特有的换行符。
for (int i = 0; i < NAMES.length; i++) {
System.out.printf("%-30s %4d %4d %4d%n",
NAMES[i], stock[i][1], stock[i][2], stock[i][3]);
}
输出:
Spa reine 25cl 56 200 55
Bru plate 50cl 42 200 60
Bru pét 50cl 62 200 125
Pepsi 45 200 150
Spa orange 25 200 140
Schweppes Tonic 72 200 86
Schweppes Agr 40 200 47
Ice Tea 48 200 80
Ice Tea Pêche 24 150 75
Jus d'orange Looza 36 200 90
Cécémel 15 100 55
Red Bull 25 80 23