0

So, I have two Strings (line and objectCode)

I want to print line first, and then print a number of spaces based on the length of line and then print objectCode. (So that all of the objectCodes are lined up.

I tried, but got output like:

0000    FIRST   ST      RETADR,LX    172028
0003            LD      BX,#LENGTH    692028
0006    CLOOP   +JSUB   RDREC    03100000

objectCode being the last numbers in each line (172028), as you can see they are not lined up like I want them to be.

So, in essence I want something like:

0000    FIRST   ST      RETADR,LX    172028
0003            LD      BX,#LENGTH   692028
0006    CLOOP   +JSUB   RDREC        03100000

I just can't seem to figure out how to get it. Thank you.

edit

What I have tried:

First try (this is what should have worked):

String write = String.format("%-45s%s", line, objectCode);
fw.write(write + "\n"); //Using a FileWriter

Second I tried (as a last ditch effort):

fw.write(line);
int numOfSpaces = 40 - line.length(); //arbitrary number to check if this works
for (int spaces = 0; spaces < numOfSpaces; spaces++) {
    fw.write(" ");
}
fw.write(objectCode);

I figured it would print less spaces for longer line lengths.. But it didn't seem to work.

EDIT

I have figured out the problem but I don't know how to solve it.

The problem is that earlier in the program I trimmed each line variable (trimming off the preceding and ending white spaces) so I could get each word in the line by itself.

So, I had:

line = input.nextLine();
words[] = line.trim().split("\\s+"); //Splitting by white space

I think the trim() method is my problem here... However, I need it in order to do what the program is intended to do.

4

1 回答 1

0

好吧,所以我想通了,并想发布答案,以防其他人遇到此问题。

所以,就像我说的那样,问题是我正在根据空格修剪行变量(以便将行中的每个单词分开):

String line = input.next
String[] words = line.trim().split("\\s+"); //Get each word by itself

问题是稍后在程序中我想在这一行之后打印一些东西。而且没有办法得到合适的行长,因为所有的空格都消失了:

0000    FIRST     ST        RETADR,LX  //line.length = 20 (no whitespace)
0003              LD        BX,#LENGTH //line.length = 16 (no whitespace)

这两行都不考虑长度中的任何空格。所以当我在这样的行之后写一些东西时(使用文件编写器)

String write = String.format("%-30s, %s", line, objectCode);
fw.write(write + "\n");

我会得到:

0000    FIRST     ST        RETADR,LX       172028
0003              LD        BX,#LENGTH            692028

这是因为当我为行 (%30s) 分配 30 个空格时,没有考虑这些空格。

为了解决这个问题,我不得不格式化行本身,而不是格式化行中的每个单词:

String write = String.format("%-10s%-10s%-10s%-10s%", word1, word2, word3, word4);
fw.write(write + "\t" + objectCode + "\n");

所以现在这有效地给了我想要的东西,因为每一行都分配了相同数量的空间,并且它们是左对齐的(-10s% 等)

0000    FIRST     ST        RETADR,LX   172028
0003              LD        BX,#LENGTH  692028
于 2015-04-12T17:02:45.863 回答