My program compiles and runs but I am not sure I am handling the StringTooLongException properly and it does not end my program when thrown, which I need it to do. Any help would be appreciated, Thanks.
//Main class
import java.util.Scanner;
public class MaxInt {
public static void main(String[] args) {
String userString;
final int MAX = 5;
int[] userInts = new int[MAX];
int tempInt = 0;
int maxValue = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter " + userInts.length + " integer values: ");
for (int i = 0; i < userInts.length; i++) {
userString = scan.next();
try {
tempInt = Integer.parseInt(userString);
} catch (NumberFormatException nfe) {
System.out.println("Please enter only integer values!");
if (i > 0)
i--; //decrements i so the loop continues until 5 successful ints have been entered.
}
try {
if (userString.length() > 5 ) { //checks if string is greater than 5 characters
throw new StringTooLongException("String must be less than 5 characters");
}
} catch(Exception e){
System.out.println(e.getMessage());
}
userInts[i] = tempInt;
if (tempInt > maxValue) {
maxValue = tempInt;
}
}
System.out.print("You entered: " );
for (int q = 0; q < userInts.length; q++) {
System.out.print(userInts[q] + " ");
}
System.out.println("\nThe maximum value entered was: " + maxValue);
}
}
public class StringTooLongException extends Exception {
public StringTooLongException(String message) {
super(message);
}
}

New Topic/Question
Reply




MultiQuote





|