I am creating an array where the user is entering boolean values, and the array will count how many true
s and false
s there are will output the number.
For example, if TorF[] = {true, false, true, true, false}
then it would output [3,2]
(three true
s and 2 false
s).
So far I have this:
public static int[] longestStreak(boolean[] values) {
Scanner input = new Scanner(System.in);
boolean TorF[] = new boolean[]
if (input == False)
{
System.out.println(TorF.length);
}
else
{
System.out.println(TorF.length);
}
return TorF;
}
Im not too sure if this is right. If someone could help me that would be much appreciated
Thank you
It's true
and false
(you can't use False
in Java). Also, you just need to count the true
(s) (because the number of falses is the total count minus the number of trues). And I would use a for-each
loop . Something like,
public static int[] longestStreak(boolean[] values) {
int trueCount = 0;
for (boolean b : values) {
if (b) {
trueCount++;
}
}
return new int[] { trueCount, values.length - trueCount };
}
or in Java 8+, something like
public static int[] longestStreak(boolean[] values) {
int trueCount = (int) IntStream.range(0, values.length)
.filter(i -> values[i]).count();
return new int[] { trueCount, values.length - trueCount };
}
Java 8 way to do the same:
List<Boolean> valuesList = values.asList();
List<Boolean> list2 = valuesList
.stream()
.map(value-> value ? trueCount++ : falseCount++)
.collect(Collectors.toList());``
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.