Write your code in the file LuckyNines.java . Use the IO module for all inputs a
ID: 3602156 • 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).
Hint: Some numbers have more than 1 nine, and not every 9 appears in the ones place.
Hint2: Nested loops are helpful
must use IO.read[data type]
you must use IO.output[data type]
you must use IO.output[data type]Answer()
Explanation / Answer
import java.io.*;
public class MyClass {
public static void main(String args[]) {
int nines = 0;
int lowerEnd=0, upperEnd=0;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter lower end: ");
lowerEnd = Integer.parseInt(reader.readLine());
System.out.print("Enter upper end: ");
upperEnd = Integer.parseInt(reader.readLine());
} catch (IOException ioe) {
ioe.printStackTrace();
}
for(int i = lowerEnd; i <= upperEnd; i++){
for(char c : String.valueOf(i).toCharArray()){
if(c == '9') nines++;
}
}
System.out.println("Total no of nines are: " + nines);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.