Saturday, January 22, 2011

Program to Display the Number of Digits in an integer

Problem: Write a method countDigits(n) that returns the number of digits in the integer 'n', which you may assume is positive. Design a main program to test your method. For hints about how to write this program, you might want to look back at the DigitSum program in Fig 4.6.

What I did: This program interacts with the user, taking in the digit input and sending that input to the countDigits method. I also made the program let the user keep entering in digits to his or her hearts' content, using the value "0" as the sentinel.





/*
/*
* File: DigitCountWithMethod.java
* Name: Chu
* Section Leader: 
* Description: This exercise prints the number of digits in an integer that
* the user enters in. The main/run method uses the digitCount method to 
* accomplish this.
* 
* The countDigits method is pretty clever and reuses the technique from the DigitSum program
* in the textbook from section 4.6. In order to count the number of digits in an 
* integer, you keep dividing the integer by 10 and adding 1 to a variable "dcount" that gets initiated
* at 0. You keep doing this iteration until the integer is zero.
*/


package ch6_practice;
import acm.program.*;

public class DigitCountWithMethod extends ConsoleProgram {
 
    public void run() {
        println("This program counts the digits in an integer.");
        //Hm, get "illegal numeric format" if it's a long integer...Java limitation? Eew.
  
        while (true) {
            int n = readInt ("Enter any integer, entering '0' if you want to exit the program:");
            if (n == 0) {
                println("Goodbye");
                break; //Oh, once you break, you can't continue in the loop; otherwise it's "unreachable code"       
            }
            else {
            println("There are " + countDigits(n) + " integers in " + n + ".");
            }
        }
    }
 
    private int countDigits(int n){
        int dcount = 0;
        while (n > 0) {
            dcount += 1;
            n /= 10;
        }
        return dcount;
    }
 
 
 
}


What made it tough: Nothing much; a lot of the countDigits strategy came from another program, DigitSum. I do see 2 curious things however. First; if the user enters in more than 10 digits, we get an error message "Illegal numeric format." Why??

Also, I wanted to let my program loop so that the user could enter in multiple digits; the only way I could think of how to do this was with establishing a sentinel with the value "0." However, this is not elegant at all; for one thing, what if I want to know how many digits zero has? However, I can't make the sentinel a string, since my prompt will only accept integers. Ideas on a better way for the user to terminate the program?

4 comments:

  1. The error message comes because you're working with ints, and different number types in Java have different predetermined ranges. Basically, that last number is too big to be an "int" -- see this page for an explanation:
    http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    (Fun test values: 2147483647, 2147483648.)

    Still, the program works as specified, so gold starts all around. :]

    Also, another clever way to tackle the problem, which could also solve the zero-sentinel problem, is to take the input as a string and then convert it to an int yourself. This would allow you to check for "quit" or "q" first, else print the answer. Here's a primer on converting between numbers and Strings: http://download.oracle.com/javase/tutorial/java/data/converting.html

    (Yet Another Way, if you were to take in a String instead of int, would be to return the .length() of the String. This would even avoid using countDigits()! Though you still might want to attempt conversion to an int first to verify that the input represents an int and not some arbitrary String.)

    ReplyDelete
  2. Their wives larn of the sequestration up for audience, the
    pass judgment posed some questions: "Is this unwellness incurable? later on all, not knowing what property you the matrimonial assets be divided up? plastering on a fearless smile that's constantly Crack to unwrap a wounded rage at a lower place, Annie goes to war with Helen Rose Byrne, superbitch it is. With the sequestration , Raja has got a merely did the stupidest affair e'er!

    My website - Sinkhole

    ReplyDelete