Solved

Help With Illegal Argument Exception

Posted on 2014-12-10
13
161 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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
oracle 11g 23 107
expectj telnet failing 5 45
Why is enum singleton a better approach than static factory 3 24
java mysql insert application 14 29
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

828 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