Write your code in the file LuckyNines.java. Use the IO module for all inputs an
ID: 3930120 • Letter: W
Question
Write your code in the file LuckyNines.java. Use the IO module for all inputs and outputs. Your task is to write a method called which counts and returns the number of nines that appear within a range of numbers. Your solution should make use of looping constructs. In main method, ask the user for the following information, in this order: The lower end of the range The upper end of the range Then call countLuckyNines (lowerEnd, upper End) with the user input values; countLuckyNines(lower End, upper End) returns the number of nines that appear in the sequence from lower end to upper end (inclusive).Explanation / Answer
LuckyNines.java
import java.util.Scanner;
public class LuckyNines {
public static void main(String s[]){
Scanner scan = new Scanner(System.in);
System.out.print("The lower end of the range: ");
int lower = scan.nextInt();
System.out.print("The upper end of the range: ");
int upper = scan.nextInt();
int count = countLuckyNines(lower, upper);
System.out.println("RESULT: "+count);
}
public static int countLuckyNines(int lowerEnd, int upperEnd){
if(upperEnd < lowerEnd){
return -1;
}
else{
int count = 0;
for(int i=lowerEnd; i<=upperEnd; i++){
for(int j=i; j>0; j=j/10){
if(j % 10 == 9){
count++;
}
}
}
return count;
}
}
}
Output:
The lower end of the range: 100
The upper end of the range: 150
RESULT: 5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.