从TextArea格式搜索的输出

时间:2018-12-08 13:45:04

标签: java string javafx text-files string-formatting

我需要您的帮助!

  

所以基本上,我制作了一个Search Student标签,该标签读取.txt文件,   在textArea上输出。

Image

但是搜索后,我接受了:

Output result

但是我想接受这个:

as Output on TextArea

这是我的代码:

 StringBuilder rsl = new StringBuilder();

    @FXML
    public void PressedSearch(ActionEvent event) throws IOException {                   //Ektelei Search sto arxeio ton mathiton
        if (searchStudent() == false) {
            result.setStyle("-fx-font:13 sherif;-fx-text-fill: red");
            result.setText("Failed to find the student");
        } else {
            result.setStyle("-fx-text-fill: black");
            rsl.setLength(0);
        }
    }

    public boolean searchStudent() throws IOException {         //Sto search o admin mporei na dei perissotera pragmata
        Path p = Paths.get("src", "inware", "users.txt");
        Scanner in = null;
        boolean i = false;
        in = new Scanner(p);
            while (in.hasNext()) {
                String line = in.nextLine();
                String[] fields = line.split("[,]");
                if (line.contains(search_field.getText())) {
                    rsl.append(fields[4] + "   " + fields[5]+ "   " + fields[6] + "   " + fields[7] + "   " + fields[8]
                            + "   " + fields[9] + "   " + fields[10]+ "   " + fields[11]+ "   " + fields[12]+ "   " + fields[13]
                            + "   " + fields[14]+ "   " + fields[15] + "   " + fields[16] + "   " + fields[17] + "   " + fields[18]
                            + "   " + fields[19] + "   " + fields[20] + "   " + fields[21]);
                    rsl.append("\n");  //Gia na kanei print polla atoma
                    i = true;
                }
            }
        result.setText(rsl.toString());
        in.close();
        return i;

1 个答案:

答案 0 :(得分:2)

尝试使用String.format(String format,Object ... args)。

代替使用:

rsl.append(fields[4] + "   " + fields[5]+ "   " + fields[6] + "   " + fields[7] + "   " + fields[8]
                        + "   " + fields[9] + "   " + fields[10]+ "   " + fields[11]+ "   " + fields[12]+ "   " + fields[13]
                        + "   " + fields[14]+ "   " + fields[15] + "   " + fields[16] + "   " + fields[17] + "   " + fields[18]
                        + "   " + fields[19] + "   " + fields[20] + "   " + fields[21]);
                rsl.append("\n");  //Gia na kanei print polla atoma

您可以使用:

String format = "%10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n";
rsl.append(String.format(format,fields[4],fields[5],fields[6],fields[7],fields[8],fields[9],fields[10],fields[11],fields[12],fields[13],fields[14],fields[15],fields[16],fields[17],fields[18],fields[19],fields[20],fields[21]));

在字符串格式中,'%'和's'(“宽度”字段)之间的数字表示要输出的最小字符数。您可以根据需要进行更改。