Why does this program run?

• November 1st, 2011, 10:09 PM
djl1990
Why does this program run?
I test for input to be of length 6, yet even if i enter 5 digits program continues to run. ?

Code :

```public class Task1b {   public static void main(String[] args) {   String input; String nUsage; int[] d = new int[10];   Scanner scan1 = new Scanner(System.in); Scanner scan2 = new Scanner(System.in);   boolean isValid = true;   // Request User Input System.out.println("Enter 6 digits: "); input = scan1.nextLine(); System.out.println("How many codewords do you want to generate?"); nUsage = scan2.nextLine();   // Ensure input is of length: 6 if (input.length() != 6) { System.out.println("Input must be 6 numbers!"); } // Prompt for a valid input if (nUsage.length() == 0) { System.out.println("Please enter a valid number"); } int n = Integer.parseInt(nUsage);   if (n <= 0) { System.out.println("Please enter a valid number"); } // Convert the String which stores the first 6 digits to an Integer int intBeginNumber = Integer.parseInt(input);   while (n > 0) { isValid = true; String strGenerate = ""; int tempNumber = intBeginNumber;   // Set d [5],d[4],....d[0] for (int i = 0; i < 6; i++) { d[5 - i] = tempNumber % 10; tempNumber /= 10; }   // d7 = (4 * d1 + 10 * d2 + 9 * d3 + 2 * d4 + d5 + 7 * d6) % 11; d[6] = (4 * d[0] + 10 * d[1] + 9 * d[2] + 2 * d[3] + d[4] + 7 * d[5]) % 11; // d8 = (7 * d1 + 8 * d2 + 7 * d3 + d4 + 9 * d5 + 6 * d6) % 11; d[7] = (7 * d[0] + 8 * d[1] + 7 * d[2] + d[3] + 9 * d[4] + 6 * d[5]) % 11; // d9 = (9 * d1 + d2 + 7 * d3 + 8 * d4 + 7 * d5 + 7 * d6) % 11; d[8] = (9 * d[0] + d[1] + 7 * d[2] + 8 * d[3] + 7 * d[4] + 7 * d[5]) % 11; // d10 = (d1 + 2 * d2 + 9 * d3 + 10 * d4 + 4 * d5 + d6) % 11; d[9] = (d[0] + 2 * d[1] + 9 * d[2] + 10 * d[3] + 4 * d[4] + d[5]) % 11;   for (int i = 0; i < 10; i++) { if (d[i] == 10) { // If i is equal to 10, then its an unusable number isValid = false; break; } else { strGenerate = strGenerate.concat(Integer.toString(d[i])); } }   if (isValid) { // Print out the generated number(s) System.out.println(strGenerate + " ");   // Decrease number usage n--; }   // Try next number intBeginNumber++; } } }```
• November 1st, 2011, 10:19 PM
Junky
Re: Why does this program run?
Of course it will unless you tell it to stop.
• November 1st, 2011, 10:29 PM
csharp100
Re: Why does this program run?
You can test for the "length" of input. i.e. if input is 5 then loop only 5 times. If 4 then loop only 4. Assign the length a variable and test against that variable.