代码在这里:
这是我目前的输出:
输出:
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.
答案 0 :(得分:1)
更简单的方法是利用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
的元素,最后使用{ {1}}获取金额:
Stream#count
如果您想返回long numTrueElements = lines.stream().filter(s -> s.equals("true")).count();
元素的总数,只需从false
行的大小中减去true
个元素的总数。
List<Stirng>
如果您想要第一个int numFalseElements = lines.size() - numTrueElements;
元素的索引,那么您可以使用true
:
List#indexOf
使用此方法,您可以完全抛弃int firstTrueIndex = lines.indexOf("true");
和任何循环。
答案 1 :(得分:0)
您可以使用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
答案 2 :(得分:0)
AMD