Q Write your code in the file LuckyNinesjava Use the IO modu

Q. 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

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).
Hint: Some numbers have more than 1 nine, and not every 9 appears in the ones place.
Hint2: Nested loops are helpful
On error (i.e. upper end is less than lower end) countLuckyNines returns -1.

Example:

Solution

// for input
import java.util.Scanner;

public class LuckyNines{
// a static method taking 2 input parameters
public static int countLuckyNines(int lowerEnd,int upperEnd)
{
// returning -1 if lowerbound is greater
if(lowerEnd > upperEnd)
return -1;
  
// Proceeding if valid
int i, help, nines = 0;
// checking every number in between lower and upper bounds
for(i=lowerEnd;i<=upperEnd;i++)
{
// counting the number of 9s in each number
help = i;
while(help>0)
{
if(help%10 == 9) // checking whether a digit is 9
nines++; // increasing nines by 1
help = help/10; // dividing by 10
}
}
// returning the number of nines
return nines;
}

// main method
public static void main(String []args){
  
// for input
Scanner sc = new Scanner(System.in);
  
// taking user input
int upperEnd, lowerEnd;
System.out.print(\"Enter lower bound: \");
lowerEnd = sc.nextInt();
System.out.print(\"Enter upper bound: \");
upperEnd = sc.nextInt();
  
// printing and calling the function countLuckyNines
System.out.printf(\"RESULT: %d\ \", countLuckyNines(lowerEnd,upperEnd));
}
}

/*
SAMPLE OUTPUT

Enter lower bound: 100
Enter upper bound: 150
RESULT: 5

Enter lower bound: 1
Enter upper bound: 100
RESULT: 20

*/

Q. 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 The lower end of the range T
Q. 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 The lower end of the range T

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site