Java 正在尝试在单独的行上打印字符串
在为非CS类编写项目时,我遇到了一个问题。我想到的这个项目是一种测验,用户被问到一个问题,并被给予多种答案选择。现在,我打算将这些问题键入一个.txt文件,并使用文件扫描仪将其读入,然后创建一系列问题,如下所示:Java 正在尝试在单独的行上打印字符串,java,Java,在为非CS类编写项目时,我遇到了一个问题。我想到的这个项目是一种测验,用户被问到一个问题,并被给予多种答案选择。现在,我打算将这些问题键入一个.txt文件,并使用文件扫描仪将其读入,然后创建一系列问题,如下所示: public static String[] questionToString(Scanner sf) { String temp = ""; String[] questions = new String[Q]; int i = 0; while(sf
public static String[] questionToString(Scanner sf) {
String temp = "";
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp += sf.nextLine();
}
questions[i] = temp;
i++;
temp = "";
return questions;
}
与之相反:
Question 1
a
b
c
d
我希望每个字符都放在自己的行上,如第二个示例中所示打印字符串时如何执行此操作?(System.out.println()
)
最后,我打算把它们放在绘图板上,下面列出问题
谢谢 使用“\n”
在已附加的行println()
之外再添加一行:
System.out.println(your_var + "\n")
这是因为您正在向字符串添加问题行。因此,对以下行进行一个小的更改:
temp += sf.nextLine() + "\n";
当然,换行符取决于您正在运行的环境(
\n
或\r\n
)。将多个字符串附加到一个字符串中的最佳方法是使用StringBuilder。我已经使用StringBuilder重写了您的代码
public static String[] questionToString(Scanner sf) {
StringBuilder temp = new StringBuilder();
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp.append(sf.nextLine());
temp.append(System.lineSeparator());
}
questions[i] = temp.toString();
i++;
temp = new StringBuilder();
return questions;
公共静态字符串[]问题字符串(扫描程序sf){
StringBuilder temp=新的StringBuilder();
字符串[]问题=新字符串[Q];
int i=0;
while(sf.hasNext()){
对于(int y=0;y<5;y++){
临时附加(sf.nextLine());
临时附加(System.lineSeparator());
}
问题[i]=临时toString();
i++;
temp=新的StringBuilder();
回答问题;
}
注意:请不要在字符串中附加
/n
,因为新行字符因不同的操作系统而异。我建议您使用system.lineSeparator()
,这将根据运行代码的操作系统添加新行字符。这段代码非常混乱。你的大括号不成对。你应该解决这个问题。我建议,在配置文件中使用JSON。你会获得更大的灵活性(也就是说,你可以有不止一行的问题/答案),配置更容易阅读,也更容易将配置读入你的程序,并以结构化的方式处理问题和答案(有问题类、答案类等)我尝试使用\n但无效,但我会再试一次。另外,最终目标不是打印字符串,而是能够将其转换为数组格式,同时保持每行之间的空格。显示使用数组问题的代码
public static String[] questionToString(Scanner sf) {
StringBuilder temp = new StringBuilder();
String[] questions = new String[Q];
int i = 0;
while(sf.hasNext()){
for(int y = 0; y < 5; y++) {
temp.append(sf.nextLine());
temp.append(System.lineSeparator());
}
questions[i] = temp.toString();
i++;
temp = new StringBuilder();
return questions;