37.0k views
5 votes
Can someone help me with my homework?

Lucky Sevens (10 points). Write a program LuckySevens.java that takes an int as a command-line argument and displays how many digits in the integer number are 7s.
Note: the number can be negative.
% java LuckySevens 3482
0
% java LuckySevens 372777
4
% java LuckySevens -2378272
2

I'm confused about how to even start

User ElDog
by
5.1k points

1 Answer

2 votes

Answer:

class Main {

public static void main(String[] args) {

if (args.length > 0) {

long count = args[0].chars().filter(ch -> ch == '7').count();

System.out.println("Number of sevens " + count);

}

}

}

Step-by-step explanation:

That would do the trick. Drop a comment if you need more explanation. It requires Java 8 because of the lambda expression. What happens is that the input is treated as a string rather than a number, because we're looking for 7's. Convert it to an array of chars, filter out only the chars that are a '7' and count them.

User Seekheart
by
4.5k points