Ok all, I'm stuck again with this code.
I need to put in an Exception that won't allow the user to input 0 (because you can't divide later by 0) and the user cannot enter alpha characters. I am trying to display the message, disregard the wrong input, and loop to allow the user to try again until they put in the acceptable number.
Here is what I have:
package exceptionhandler;
/**
*
* @author Sarah
*/
import java.util.Scanner;
public class ExceptionHandler {
/**
* @param args
* the command line arguments10 10
*/
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Please enter ten values:");
System.out.println();
// Input the data into array from the user.
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
try
{
for (int i = 1; i < digit.length; i++) {
System.out.print("Value " + i + ": ");
digit[i] = (double)in.nextInt();
sum += (int)digit[i];
}
catch (NumberFormatException e)
{
System.out.println("You Can Only Enter Numbers!");
}
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
I have tried declaring the throw exception and then tried a try..catch. But it is not recognizing catch and try talking to one another... so I know I am doing something wrong, but I can't see where it should go.
Is the Exception in the right place? Should I have done something else? Is my exception written wrong? How can I then move on to prevent the input of zero as well- rethrow?
Help?