Solved

Help With Illegal Argument Exception

Posted on 2014-12-10
13
127 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
strCount chalenge 3 51
java  and programming certification ? 4 65
Problem to start Neon 20 54
Image decoding from Camera 3 48
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
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…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

746 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

9 Experts available now in Live!

Get 1:1 Help Now