如何在不更改格式的情况下删除所有空格,以及这样做的最佳选择是什么,如果这样做,我将使用System.out.printf();或其他一些指令。请使用Java而不是C ++进行响应。我真的很感谢任何能提供帮助的人,并非常感谢他们为我解决自己的问题。
public class WorldPopulation{
//main string
public static void main(String[] args) {
//prints title
System.out.println(" This is a estimate of world population growth within 300 year time span. ");
//prints number value
System.out.println(" Numbers are in millions");
//number of rows and columns
final int ROWS = 6;
final int COLUMNS = 7;
//population numbers array
int [] [] populations =
{
{106, 107, 111, 133, 221, 767, 1766},
{502, 635, 809, 947, 1402, 3634, 5268},
{2, 2, 2, 6, 13, 30, 46},
{163, 203, 276, 408, 547, 729, 628},
{2, 7, 26, 82, 172, 307, 392},
{16, 24, 3, 74, 167, 511, 809}
};
//continents array
String[] continents =
{
"Africa",
"Asia",
"Australia",
"Europe",
"North America",
"South America"
};
//prints the years used in the estimation
System.out.println(" Year 1750 1800 1850 1900 1950 2000 2050");
//print population data
for (int i = 0; i < ROWS; i++)
{
//print i'th row
System.out.printf("%20s", continents[i]);
//prints the columns and the rows
for (int j = 0; j < COLUMNS; j++) {
System.out.printf("%5d", populations [i] [j]);
}
System.out.println(); //start new line at end of row
}
//print column totals
System.out.printf("%20s","World total");
//prints the total estimated population in the years used
for (int j = 0; j < COLUMNS; j++)
{
int total = 0;
for (int i = 0; i < ROWS; i++) {
total = total + populations[i][j];
}
//format of the printed totals
System.out.printf("%5d", total);
}
//starts new line after each row
System.out.println();
}
//end of class and program.
}
答案 0 :(得分:0)
您可以执行以下操作:
System.out.format("%15s%s", "", "Test");
您有一个长度为15的字符串,后跟一个未定义的字符串。因为第一个要格式化的字符串是一个空字符串,所以将打印15个空格。
答案 1 :(得分:0)
您需要用以下行替换您的行:
System.out.printf("%16s%s\n"," ","Year 1750 1800 1850 1900 1950 2000 2050");
如您所见,我输入了两个格式参数:
%16s
for " "
%s
for "Year 1750 1800 1850 1900 1950 2000 2050"
除了format参数之外,我还用\n
换行了。