我是java和for循环的新手。我希望我的代码打印出来
Andy **
Kristy **********
Amy ***** `
但是我得到了这个
Andy **
Kristy **********
Amy *****
如何更改for循环以停止与这种名称的间距?谢谢。
public static void drawChart(String name, int age) {
System.out.print(name);
for(int j = 1; j <= 10; j++) {
System.out.print(" ");
}
for (int i=0; i<age; i++) {
System.out.print("*");
}
System.out.println(" ");
}
答案 0 :(得分:4)
您可以使用<http://example.com>
实用程序以特定宽度写入名称。如果名称小于该宽度,它将用空格填充其余部分。这样的事情。
Title
**Bold**
这里,这部分String.format()
正在用20个字符写下名字。首先它写入名称,然后是空格,直到它达到20个字符。
答案 1 :(得分:2)
您可以使用名称长度函数打印多个空格,而不是打印10个空格:
System.out.print(name);
for(int j = 1; j <= 20 - name.length(); j++) { // the value 20 should be
// higher than the longest name
System.out.print(" ");
}
for (int i=0; i<age; i++) {
System.out.print("*");
}
System.out.println(" ");
答案 2 :(得分:2)
如果您使用的是Java 8,则可以使用String::join,如下所示:
public static void drawChart(String name, int age) {
String spaces = String.join("", Collections.nCopies(20 - name.length(), " "));
String stars = String.join("", Collections.nCopies(age, "*"));
System.out.println(name + spaces + stars);
}
答案 3 :(得分:0)
上述答案很好,但是当您调用名称最长的函数时,他们不会考虑这种情况,然后再使用下一个最长名称再次调用该函数。在这种情况下,间距会有所不同。 以下是适当考虑该问题的解决方案:
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Map;
import java.util.Set;
public class Search {
public static void drawChart(Multimap<String, Integer> persons){
//we use Multimap because we may have more than one person with the same name
Set<String> names = persons.keySet();
int maxLength = 0;
for (String name : names) {
if (name.length() > maxLength) {
maxLength = name.length(); //define the longest name
}
}
for (Map.Entry<String, Integer> entry : persons.entries()) {
String name = entry.getKey();
System.out.print(name);
if (name.length() < maxLength) {
//adjusting the number of spaces required to be on the same level
//with the longest name
int diff = maxLength - name.length();
for (int i = 0; i < diff; i++) {
System.out.print(" ");
}
}
Integer age = entry.getValue();
for (int i = 0; i < age; i++) {
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args) {
Multimap<String, Integer> map = ArrayListMultimap.create();
map.put("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 2);
map.put("ffffffffffffffffffffffffffffffffffffffffffffffffff" +
"fffffffffffffffffffffffff", 3);
map.put("zz", 3);
map.put("zz", 6);
map.put("ffff", 9);
drawChart(map);
}
}
输出:
zz ***
zz ******
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ***
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa**
ffff *********