如何用逗号在一行显示文件的输出?
代码是在这里:如何用逗号在一行显示文件的输出?
这里是我的电流输出:
OUTPUT:
Integer Array Contents:
, -3, 2, 0, 0, 1, -5
Total odd numbers: 3
Odd numbers are: -3 1 -5 0 0 0
Index of last zero: 3
Minimum: -5
Maximum: 2
Sum: -5
Element mean is: 0.0
//1) How do I get rid of the random "," at the beginning? Lol
//2) How do I get rid of the 0's that are in the "Odd numbers are: " category.
//3) Mean's not working. What should I do to fix that. Maybe it has something to do
//with the extra zeroes? I made it into a double and that didnt do anything either.
您可以使用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 (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"));
(firstindex > -1 ? firstindex : "No true in file")
意味着如果输入== -1打印没有真正在文件其他打印索引
输出
Welcome to the Info-Array Program!
Please enter the filename for the Boolean values: Boolean Array Contents:
true,true,false,true,false,true
Total TRUEs: 4
Total TRUEs: 2
Index of first TRUE: 0
一个更简单的方法来完成,这将是利用Files#readAllLines
读取File
的每一行变成List<Stirng>
。然后,您可以使用String#join
轻松地将每个String
与逗号作为分隔符组合使用。
List<String> lines = Files.readAllLines(file.toPath());
String fileContents = String.join(",", lines);
如果你想返回true
元素的总数量,只是Stream
的List<String>
并过滤掉等于true
的元素,最后使用Stream#count
获得量:
long numTrueElements = lines.stream().filter(s -> s.equals("true")).count();
如果要返回false
元素的总数,只需从List<Stirng>
行的大小中减去true
元素的总数。
int numFalseElements = lines.size() - numTrueElements;
如果你想第一true
元素的索引,那么你可以使用List#indexOf
:
int firstTrueIndex = lines.indexOf("true");
使用这种方法,你可以沟Scanner
和任何环路完全。
这是一个很好的回答,使用java 8,你只需要像这样改变'int'到'long' long numTrueElements = lines.stream()。filter(s - > s.equals(“true”))。count() ; (+ 1)** –
@YCF_L谢谢你,我已经倒过来了。这是一个很好的例子。 –
@JacobG。如果你不改变它,代码将不会编译。加上有**没有**自动** downcast **。 **扩大**是自动缩小**是明确的。 –
String line=null;
while (scan.hasNextLine()) {
line += scan.nextLine()+",";
}
System.out.println("Boolean Array Contents: "+line);
int count = line.split(",").length;
您的代码请 –
在Pastebin中。 – way245