My program compiles and runs fine:
import java.util.*; public class Chapter5Ex1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { String input = ""; int sum = 0, length, add = 1, counter = 0, counter2 = 0; long number; boolean found = false; counter = 0; System.out.println("Enter an integer: "); System.out.println(); input = console.next(); number = Math.abs(Long.parseLong(input)); input = Long.toString(number); length = input.length(); //System.out.println("the length is: " + length); System.out.print(input.substring(0, 1)); while(counter < length - 1) { System.out.print(" " + input.substring(add, add + 1)); add++; counter++; } while(counter2 < length) { sum += number % 10; number /= 10; counter2++; } System.out.print(" " + "The sum is: " + sum + "\n" + "\n"); } }
but I want it to prompt the user again for another integer after the program executes. I have tried a few different loops, sentinel, flagged,
but the second time it runs it gives me out of bonds exception for the counter variable. I have even tried initializing the counter to zero just outside the while(counter < length - 1) loop but I always get that out of bounds exception. Here is an example of the flag controlled loop I tried.
import java.util.*; public class Chapter5Ex1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { String input = ""; int sum = 0, length, add = 1, counter = 0, counter2 = 0; long number; boolean found = false; while(!found) { counter = 0; System.out.println("Enter an integer: "); System.out.println(); input = console.next(); number = Math.abs(Long.parseLong(input)); input = Long.toString(number); length = input.length(); //System.out.println("the length is: " + length); System.out.print(input.substring(0, 1)); while(counter < length - 1) { System.out.print(" " + input.substring(add, add + 1)); add++; counter++; } while(counter2 < length) { sum += number % 10; number /= 10; counter2++; } System.out.print(" " + "The sum is: " + sum + "\n" + "\n"); } } }