我想在小数点处对齐一列浮点数。我知道如果你限制小数点后的点很容易,但我希望用户能够输入无限数量和长度的浮点数。
这是我的程序中处理浮动对齐的部分:
String[] input = new String[3];
System.out.format("%n%n\tEnter three floating point numbers%n");
for (int i=0;i<3;i++)
input[i] = in.nextLine();
System.out.format("\tHere they are lined up on their decimal point%n");
/*This is used to find decimal location in each string*/
int[] decLoc = new int[3];
for (int i=0; i<3; i++)
{
for(int j=1; j<=input[i].length();j++)
if(input[i].charAt(j-1) == '.')
decLoc[i] = j;
}
/*print 5 spaces before number if the decimal is at place 0, 4 spaces for 1...*/
for(int i=0;i<3;i++)
{
if(decLoc[i]==0) System.out.print(" ");
else if(decLoc[i]==1) System.out.print(" ");
else if(decLoc[i]==2) System.out.print(" ");
else if(decLoc[i]==3) System.out.print(" ");
else if(decLoc[i]==4) System.out.print(" ");
else if(decLoc[i]==5) System.out.print(" ");
System.out.println(input[i]);
}
输出:
Enter three floating point numbers
3265.3265
23.365
254.3256
Here they are lined up on their decimal point
3265.3265
23.365
254.3256
需要更好的解决方案来对齐不同长度的浮动。