Solved

Help With Illegal Argument Exception

Posted on 2014-12-10
13
142 Views
Last Modified: 2014-12-14
Hi,

I am trying to make this code display an IllegalArgumentException if the scores entered in the array are <-1 or >100

I am working with the Try/Catch block but how can I make it do what I want?

import java.util.Scanner;

import javax.swing.JOptionPane;


public class TestScores
{
   public static void main(String[] args)
   {
	   boolean hasError = false;
      int numScores;    // To hold the number of scores
      
      // Create a Scanner object for keyboard input.
      Scanner keyboard = new Scanner(System.in);
      
      // Get the number of test scores.
     System.out.print("How many test scores do you have? ");

      numScores = keyboard.nextInt();

      // Create an array to hold the test scores.
      double[] scores = new double[numScores];
      
      // Get the test scores and store them
      // in the scores array.
      for (int index = 0; index < numScores; index++)
      {
    	  try 
    	  {
         System.out.print("Enter score #" +
                         (index + 1) + ": ");
         scores[index] = keyboard.nextDouble();
      }catch (IllegalArgumentException ex)
    	  {
    	  hasError = true;
		  JOptionPane.showMessageDialog(null, "Invalid Score");
    	  }
      }
      
      // Create a Grader object, passing the
      // scores array as an argument to the
      // constructor.
      Scores myGrader = new Scores(scores);
            
      // Display the adjusted average.
      System.out.println("Your average is " +
                         myGrader.getAverage());
      
      // Display the lowest score.
      System.out.println("Your lowest test score was " +
                         myGrader.getLowestScore());
      
   }

Open in new window

0
Comment
Question by:Computer Guy
  • 7
  • 6
13 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 40491300
I would have thought it better to catch an out-of-range confinement, rather than try to raise an Exception on an otherwise correct type.
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40491310
Can you please provide a sample?
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40491333
Well, given >>scores[index] = keyboard.nextDouble();<<,  then why not just something like >if(scores[index] <-1||scores[index] >100){doSmthg();}
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40491342
Also with my posted code, if I enter in 50, 60 ,70 the average score is is suppose to be 60, but the program says 65.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40491365
Can't see the rest of your code, or how the average is arrived at.
0
 
LVL 16

Accepted Solution

by:
krakatoa earned 500 total points
ID: 40491636
IllegalArgumentException is thrown when you pass an illegal type to a method. But you are using it to try to catch an unwanted arithmetical value, so there is no implied exception.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 3

Author Comment

by:Computer Guy
ID: 40492467
SO like this?
   for (int index = 0; index < numScores; index++)
      {

    			  
         System.out.print("Enter score #" +
                         (index + 1) + ": ");
         if(scores[index] <-1||scores[index] >100)
		  {
			  JOptionPane.showMessageDialog(null, "Invalid Score");
		  }else{
         scores[index] = keyboard.nextDouble();
		  }

Open in new window

0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40492481
Well, yeah, I guess it looks ok - haven't tried it. Have you?

But it looks like you post the input value to the array in any case, even if it's wrong . . . is that what you want?
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40492486
I have tried it and it did not work.

I want to throw an error if the grade is <-1 or >100
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40492554
Based in the users input of the grade they enter.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40492636
import java.util.Scanner;

import javax.swing.JOptionPane;


public class TestScores
{
   public static void main(String[] args)
   {
	   boolean hasError = false;
      int numScores;    // To hold the number of scores
      
      // Create a Scanner object for keyboard input.
      Scanner keyboard = new Scanner(System.in);
      
      // Get the number of test scores.
     System.out.print("How many test scores do you have? ");

      numScores = keyboard.nextInt();

      // Create an array to hold the test scores.
      double[] scores = new double[numScores];
      
      // Get the test scores and store them
      // in the scores array.
      for (int index = 0; index < numScores; index++)
      {
    	  try 
    	  {
         System.out.print("Enter score #" +
                         (index + 1) + ": ");
         scores[index] = keyboard.nextDouble();
		 if(scores[index]<-1||scores[index]>100){ throw new IllegalArgumentException();}
      }catch (IllegalArgumentException ex)
    	  {
    	  hasError = true;
		  JOptionPane.showMessageDialog(null, "Invalid Score");
    	  }
      }
      
      // Create a Grader object, passing the
      // scores array as an argument to the
      // constructor.
      //Scores myGrader = new Scores(scores);
            
      // Display the adjusted average.
      //System.out.println("Your average is " +
                         //myGrader.getAverage());
      
      // Display the lowest score.
      //System.out.println("Your lowest test score was " +
                         //myGrader.getLowestScore());
      
   }}

Open in new window

0
 
LVL 3

Author Comment

by:Computer Guy
ID: 40492650
Thanks!

With that code, if I enter -1 as the first option there is no error.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40492656
or . . . based on what I first said, and not using Exceptions :

import java.util.Scanner;

import javax.swing.JOptionPane;


public class TestScores
{
   public static void main(String[] args)
   {
	   boolean hasError = false;
      int numScores;    // To hold the number of scores
      
      // Create a Scanner object for keyboard input.
      Scanner keyboard = new Scanner(System.in);
      
      // Get the number of test scores.
     System.out.print("How many test scores do you have? ");

      numScores = keyboard.nextInt();

      // Create an array to hold the test scores.
      double[] scores = new double[numScores];
      
      // Get the test scores and store them
      // in the scores array.
      for (int index = 0; index < numScores; index++)
      {
    	  //try 
    	  //{
         System.out.print("Enter score #" +
                         (index + 1) + ": ");
         scores[index] = keyboard.nextDouble();
		 if(scores[index]<-1||scores[index]>100){ //throw new IllegalArgumentException();}
      //}catch (IllegalArgumentException ex)
    	  //{
    	  hasError = true;
		  JOptionPane.showMessageDialog(null, "Invalid Score");
    	  //}
      }}
      
      // Create a Grader object, passing the
      // scores array as an argument to the
      // constructor.
      //Scores myGrader = new Scores(scores);
            
      // Display the adjusted average.
      //System.out.println("Your average is " +
                         //myGrader.getAverage());
      
      // Display the lowest score.
      //System.out.println("Your lowest test score was " +
                         //myGrader.getLowestScore());
      
   }}

Open in new window


-----------

btw this earlier comment of mine was horse :
"But it looks like you post the input value to the array in any case, even if it's wrong . . . is that what you want?"

I didn't read the code flow properly after the exception clause.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 39
JAVA part two 5 57
micro services spring boot application error 3 143
Basic Java Case or If-Else statement... 3 43
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video teaches viewers about errors in exception handling.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now