Hi
About to start a maths degree and what with the computer age opening up at the business-side I figure having programming experience will help on a CV. So, yesterday morning I started reading Java: A Beginner's Guide (The one you can preview from Oracle's website). Today I wrote my first proper program: this iterative code to print out the digital root of a number (you keep summing its digits until you get a 1-digit number). Here is my code:
package test; public class DigitalRootTest { public static void main(String args[]) throws java.io.IOException { System.out.println("Type in a whole number and press ENTER."); int sum = 0, num = (int) System.in.read(); boolean failedinput = false; while(num != 13) { //I put this here to break the loop of skimming characters off the end of the buffer since a carriage return is 13 in Unicode if(num < 48) { //The digits 0-9 span the range 48-57 in Unicode System.out.println("Invalid input. Please enter a whole number."); failedinput = true; break; } else if(num > 57) { //The digits 0-9 span the range 48-57 in Unicode System.out.println("Invalid input. Please enter a whole number."); failedinput = true; break; } else { num -= 48; //Converting the digits from Unicode integers to their actual values sum += num; //Totalling up the digits as they're skimmed from the buffer num = (int) System.in.read(); // getting a new character } } System.out.println(sum); if(failedinput == false) { while(sum > 9) { int i, lastdigit, worksum = sum, lim = 1 + (int) Math.log10(sum); /* i is a counting variable worksum is just a copy of sum that I can operate on safely without messing up the end result lastdigit is a variable just to hold the last digit of the current worksum as I work on it lim is a limit to be imposed on the for loop below, which is just the number of digits of the sum */ sum = 0; //reset the sum for(i = 1; i <= lim; i++) { lastdigit = worksum % 10; //get the last digit of the worksum sum += lastdigit; worksum -= lastdigit; worksum = (int) worksum/10; //Note } System.out.println(sum); } } } }
Note: I realised here I can omit the line where I take the last digit off the worksum since casting to an integer would lop this off anyway.
Can I get some feedback on this code? Can anyone spot a case in which it would fail (I haven't found one yet through putting in some large-ish numbers)? Also, how can I extend the code to send it back to the start after completing an operation? Would sticking it in an infinite for loop be okay or is that frowned upon?