Reputation: 47
Code is here:
Here is my current output:
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.
Upvotes: 0
Views: 75
Reputation: 29700
An easier way to accomplish this would be to utilize Files#readAllLines
which reads every line of a File
into a List<Stirng>
. Then, you can use String#join
to easily combine every String
with a comma as a delimiter.
List<String> lines = Files.readAllLines(file.toPath());
String fileContents = String.join(",", lines);
If you want to return the total number of true
elements, simply Stream
the List<String>
and filter out the elements that are equal to true
, and finally use Stream#count
to get the amount:
long numTrueElements = lines.stream().filter(s -> s.equals("true")).count();
If you want to return the total number of false
elements, simply subtract the total number of true
elements from the size of the List<Stirng>
of lines.
int numFalseElements = lines.size() - numTrueElements;
If you want the index of the first true
element, then you can use List#indexOf
:
int firstTrueIndex = lines.indexOf("true");
With this method, you can ditch the Scanner
and any loop entirely.
Upvotes: 1
Reputation: 59988
You can use System.out.print
instead with a comma like this:
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")
mean if the input == -1 print No true in file else print the index
Output
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
Upvotes: 0
Reputation: 2480
String line=null;
while (scan.hasNextLine()) {
line += scan.nextLine()+",";
}
System.out.println("Boolean Array Contents: "+line);
int count = line.split(",").length;
Upvotes: 0