Solved

Help With Illegal Argument Exception

Posted on 2014-12-10
13
145 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
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

 
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
 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB Script to add site to Java Exception List 4 76
rhino JavaScript import, load 25 82
oracle 11g 23 80
How to convert from xls to xlsx using java 7 39
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

770 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