In: Computer Science
Code screenshot:
Sample Outputs:
Code to copy:
import java.util.Scanner;
import java.text.DecimalFormat;
public class limit
{
public static void main(String args[])
{
// declare an object of Scanner s to take user input
Scanner s = new Scanner(System.in);
// a boolean to check whether any number without 4 as a digit
exists in the range
boolean nonumbers = true;
// receive input for first number
System.out.print("Input first number: ");
int a = s.nextInt();
// receive input for second number
System.out.print("Input second number: ");
int b = s.nextInt();
// check if both number are 4 digits
if(a<=999 && a>=100 && b<=999 &&
b>=100)
{
// declare low and high
int low, high;
// check if a greater than b
if(a>b)
{
// then assign high as a and low as b
high = a;
low = b;
}
else
{
// otherwisem, assign high as b and low as a
low = a;
high = b;
}
// iterate from low to high
for(int i = low; i<=high; i++)
{
// preserve the value of current i to number
int number = i;
// loop till number greater than 0
while (number > 0)
{
// if the last digit of current value of number is 4
if (number % 10 == 4)
// Break loop
break;
// divide number by 10 to get next digit in next iteration
number = number / 10;
}
// if now number is 0 that means all digits of i is differant from
4
// because otherwise the loop would have break in between
resulting
// in number having value above 0
if(number==0)
{
// then print value of i
System.out.print(i + ", ");
// reset nonumbers as we found a number withou 4 as digit
nonumbers = false;
}
}
}
else
{
// print invalid numbers
System.out.println("Invalid numbers. Please input two 3 digit
numbers");
}
if(nonumbers == true)
// if nonumbers is still true, print no numbers in range
System.out.println("No numbers within range without 4 as a
digit");
}
}