Solved

Help With Illegal Argument Exception

Posted on 2014-12-10
13
180 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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 learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

734 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