我在单列中有一个字符串列表。我想从这些字符串中创建三列,然后将输出打印到另一个文件。我该怎么做?
这是我到目前为止所尝试的内容:
ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
我的输入数据:
City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr
我的预期输出:
City Gsk Relocation
sripallu here jrajesh
gurgaon unitech StatisticsThreads
WizOty LTDParsvnathK Quotesby
newest PMaashuktr Loans
.
.
.
.
.
.
.
答案 0 :(得分:1)
您可以在类中输出您的需求,例如输出,并列出输出。
public class Output{
private String str1;
private String str2;
private String str3;
<geter & setter method>
}
...
ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();i = ++i%3;
if(i==0){
op = new Output();
op.setStr1(line);
}else if(i==1)
op.setStr2(line);
else
op.setStr3(line);
}
答案 1 :(得分:0)
我拿了你的代码并对其进行了一些修改:
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
int itemsOnRow = 0;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.print (line + " ");
itemsOnRow++;
if (itemsOnRow == 3)
{
itemsOnRow = 0;
System.out.println ();
}
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
下次你应该尝试实现它。如果您失败但发布了您编写的代码,那么此处的人员可以更轻松地为您提供帮助。