Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write your code in the file LuckyNines.java. Use the IO module for all inputs an

ID: 3930138 • 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, upperEnd) with the user input values; countLuckyNines(lowerEnd, upperEnd) 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