gpt4 book ai didi

java - 在java中的特定位置在文本文件中写一个单词

转载 作者:行者123 更新时间:2023-11-30 21:28:32 26 4
gpt4 key购买 nike

我正在编写一个项目,其中我必须在文本文件中写入 MySQL 数据库中的问题和标记(问题和标记在数据库中的不同列中,但在同一个表中)。在这里,我想在相同的位置写标记,即在每个问题之后垂直对齐。

我尝试使用\t 但它无法获得所需的输出

while(myRs.next()) {
String question = myRs.getString("question");
String marks = myRs.getString("questionMarks");
try {
file.write(question+"\t\t\t\t\t\t\t" + marks + "\n");//write to text file
}
catch(Exception exe) {
System.out.println(exe);
}
System.out.println("Q" + count +". " + question);
}

期望的输出是:

(单个“.”表示实际输出中的空格,“Question1”、“Question2”、“Question3”不是实际问题,而是语句)

Q1. Question1.............................4

Q2. Question2.............................4

Q3. Question3.............................5

实际输出为:

Q1. Question1........................ 4

Q2. Question2................................4

Q3. Question3...........................5

最佳答案

您只需要计算问题的大小并将剩余的空格添加到您喜欢的行大小即可。

有关重复字符的替代方法,请参阅 add characters n-times

int maxlinesize = 40;
int count=0;

while(myRs.next()) {
String question = myRs.getString("question");
String marks = myRs.getString("questionMarks");
count++;
String q="Q"+count+" "+question;
StringBuffer buffer = new StringBuffer();
buffer.append(String.join(q, java.util.Collections.nCopies(maxlinesize - q.length(), " ")))
.append(marks);
try {
file.write(buffer.toString()+ "\n");//write to text file
}
catch(Exception exe) {
System.out.println(exe);
}
}

关于java - 在java中的特定位置在文本文件中写一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com