Construct0r
Construct0r

Reputation: 55

Number of Occurrences (No Array)

I'm trying to determine how many times the number four appears in a sequence of numbers. There is a lower bound and upper bound (inclusive) that the user can determine. My code so far only counts the number of times the number 4 occurs if the range is set 40-49-- the resulting output is 10, however the actual value should be 11 because 44 has two 4's. In addition, the output for a range of 1-10 should be 1 but instead I get a value of zero? Am I not properly checking for the occurrence of 4? I'm taking into account the difference places (one's, tenths, hundredths place).

Scanner scan = new Scanner(System.in);
    int count = 0;
    int i;

    System.out.println("Enter the lower range: ");
    int lower = scan.nextInt();

    System.out.println("Enter the upper range: ");
    int upper = scan.nextInt();

    if (lower > upper) {
        System.out.println("Bad input");
    }
    for (i = lower; i <= upper; i++) {
        if (lower * 0.01 == 4) {
            count++;
        } else if (lower * .1 == 4) {
            count++;
        } else if (lower * 1 == 4) {
            count++;
        }
    }

    System.out.println("Result: " + count);

Upvotes: 1

Views: 226

Answers (2)

Ramesh
Ramesh

Reputation: 210

Below Java Code will solve your problem:

try (Scanner scan = new Scanner(System.in)) {
            int count = 0;
            int i;

            System.out.println("Enter the lower range: ");
            int lower = scan.nextInt();

            System.out.println("Enter the upper range: ");
            int upper = scan.nextInt();

            if (lower > upper) {
                System.out.println("Bad input");
            } else {
                int num=0;
                for (i = lower; i <= upper; i++) {
                    num=i;
                    while(num>0){
                        if(num%10==4){
                            count++;
                        }
                        num=num/10;
                    }
                }
                System.out.println("Result: " + count);
            }
        }

Note: When IF execute it not means below code will not execute. just write else part or exit program.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361635

Don't use floating point math. The results are subject to accuracy errors. Stick to integer arithmetic.

Hint: Use modulus % and division / to pull out particular digits.

Upvotes: 1

Related Questions