Java 如何用逗号在一行上显示文件的输出?
代码如下: 这是我当前的输出: 输出: 您可以使用System.out.print代替逗号,如下所示:Java 如何用逗号在一行上显示文件的输出?,java,file,Java,File,代码如下: 这是我当前的输出: 输出: 您可以使用System.out.print代替逗号,如下所示: int trues = 0; int falses = 0; int firstindex = -1;//first index init with -1 to check with it later String del = ""; int i = 0; while (scan.hasNextLine()) { String line = scan.next(); if (l
int trues = 0;
int falses = 0;
int firstindex = -1;//first index init with -1 to check with it later
String del = "";
int i = 0;
while (scan.hasNextLine()) {
String line = scan.next();
if (line.equals("true")) {//if the line equal true then trues++;
if (firstindex == -1) {//if the first index == -1 then assign
//it to i number of words
firstindex = i;
}
trues++;
} else if (line.equals("false")) {//if the line equal false falses++
falses++;
}
System.out.print(del + line);
del = ",";
i++;
}
System.out.println();
System.out.println("Total TRUEs: " + trues);
System.out.println("Total TRUEs: " + falses);
System.out.println("Index of first TRUE: " +
(firstindex > -1 ? firstindex : "No true in file"));
第一索引>-1?firstindex:No true in file表示如果输入==-1,则在文件中打印No true,否则打印索引
输出
实现这一点的一个更简单的方法是利用filereadalllines,它将文件的每一行读取到一个列表中。然后,可以使用Stringjoin轻松地将每个字符串与逗号作为分隔符组合
List<String> lines = Files.readAllLines(file.toPath());
String fileContents = String.join(",", lines);
如果要返回false元素的总数,只需从行列表的大小中减去true元素的总数
int numFalseElements = lines.size() - numTrueElements;
如果需要第一个true元素的索引,则可以使用ListindexOf:
使用此方法,您可以完全放弃扫描仪和任何循环。请将您的代码…放在粘贴箱中。这很好!我怎样才能得到更理想的结果,计算出正确和错误的总数,然后计算出第一个的指数?这真的是一个不好的否决投票的行为为什么是否决投票,我错在哪里?不知道,我没有否决投票。你的帮助是目前为止最好的@YCF_Lthank you@Ousmane Mahy Diaw我真的不知道为什么人们在没有投票的情况下投票反对reason@YCF_L你的答案是正确的,考虑到OP甚至说你的答案是迄今为止最好的帮助。我看不出投反对票的理由,但我想你必须接受它,继续前进^^这是一个很好的答案,使用java 8,您只需将int更改为long,就像long numTrueElements=lines.stream.filters->s.equalstrue.count;长numfalseeelements=lines.size-numTrueElements;因为count返回long而不是int+1@YCF_L谢谢,我把它倒过来了。@JacobG。如果不更改它,代码将无法编译。此外,也没有自动向下投射。加宽是自动的,变窄是明确的。
String line=null;
while (scan.hasNextLine()) {
line += scan.nextLine()+",";
}
System.out.println("Boolean Array Contents: "+line);
int count = line.split(",").length;
long numTrueElements = lines.stream().filter(s -> s.equals("true")).count();
int numFalseElements = lines.size() - numTrueElements;
int firstTrueIndex = lines.indexOf("true");
String line=null;
while (scan.hasNextLine()) {
line += scan.nextLine()+",";
}
System.out.println("Boolean Array Contents: "+line);
int count = line.split(",").length;