开发者

Java error: cannot find symbol

Help don't know what to do, why i'm getting this error.

Score.java:44: cannot find symbol
symbol  : class InvalidTestScore
location: class Score
        catch (InvalidTestScore e)
               ^
1 error



// George Beazer

import javax.swing.*; 
import javax.swing.JOptionPane;

public class Score 
    { 
        public static void main(String[] args) 
    { 
        int numberofTests = 0; 

        double[] grade = new double[numberofTests]; 

        double startgrade = 0; 

        int x = 1 ; 

        String strInput; 

        // Get how many tests are used 

        strInput = JOptionPane.showInputDialog(null, "How many tests do you have? "); 
        numberofTests = Integer.parseInt(strInput); 

        grade = new double[(int) numberofTests]; 

        do 

        { 
            for (int index = 0; index < grade.length; index++) 
        { 

            strInput = JOptionPane.showI开发者_运维技巧nputDialog(null, "Enter Test Score." + (index + 1)); 
            grade[index] = Double.parseDouble(strInput); 

            if (grade[index] < 0 || grade[index] > 100 ) 
            { 
                try 
                {  

                    x=1;
                } 

        catch (InvalidTestScore e)

            { 
                    e.printlnStackTrace();
                    System.out.println ("Choose a test score between 0 and 100");
            }

            }

            else
            {
                x=2;
            }


        {  

            System.out.println ("Choose a test score between 0 and 100"); 
        } 
    } 

} 
        while (x==1); 

        for (int index = 0; index < grade.length; index++ ) 

        { 
            startgrade += grade[index]; 
        } 

        double average = startgrade/grade.length; 

        System.out.println("The average is: " + average); 

} 
}


It is telling you that the class InvalidTestScore could not be found. Have you imported it?


Is InvalidTestScore defined in the package you are in? If not you need to add an import for it.


Okay. So. The hardest problem you're trying to solve with this snippet of code is "What happens if someone tries to enter a grade that is out of bounds?" If someone enters a score of, say, "-15", well, that'd obviously be an error!

I'm not sure if your homework requires that you use an "exception" to handle the error. If not, then I would not use try{}/catch{} for this problem, since that is overkill. But first let's look at your code:

if (grade[index] < 0 || grade[index] > 100 ) 
{ 
   try 
   {  
      x=1;
   } 
   catch (InvalidTestScore e)
   { 
      e.printlnStackTrace();
      System.out.println ("Choose a test score between 0 and 100");
   }
}
else
{
   x=2;
}

And more specifically:

   try 
   {  
      x=1;
   } 

So. What does this block mean? It says "Hey Java, try to do the stuff inside this try{} block. If it throws an error, then jump to the catch{} block." In this case, the stuff inside the try{} block is "x=1". The question becomes, "will the statement x=1 ever throw an exception?" In this program, no, it will not. The program will do just what it says - assign the value "1" to the variable "x". The try/catch here serves no purpose. It's not trapping the real error.

And the real error, of course, is whether the user inputs an invalid number. Checking for that might look like this:

if (grade[index] < 0 || grade[index] > 100 ) 
{ 
    System.out.println("Choose a test score between 0 and 100");
    break;
}

This is saying that if the grade is out of bounds, then print the error message. "break;" means "exit the loop" - to stop selecting grades.

Now on to your actual error. "InvalidTestScore" not found. In Java, if you are going to use a variable or object, you have to define it first. When you say "catch (InvalidTestScore e)" you are telling java "If there is an error, then we will throw an exception. There are many types of exceptions, but we are looking for an InvalidTestScore."

Well, Java doesn't include an InvalidTestScore type of exception. Java comes with NullPointerExceptions and ArrayIndexOutOfBound exceptions, but not an InvalidTestScore. Which means that if you want to use an InvalidTestScore exception, you've gotta write your own! (How to do so is beyond the scope of this answer.)

But you haven't written your own. So Java doesn't know where to find it. T*hus the error "cannot find" symbol.*

So, there are some other issues with your code - loops that don't need to be there, etc etc. I recommend you open up a blank .java file and start one line at a time. First write this much code:

   strInput = JOptionPane.showInputDialog(null, "How many tests do you have? "); 
   numberofTests = Integer.parseInt(strInput); 
   System.out.println(numberofTests);

Compile and run the program. Make sure those 3 lines do what you expect. If it doesn't, then get that part working perfectly. Then move on to the next portion of code:

  for (int index = 0; index < grade.length; index++) /* etc */

By building your program incrementally, and by compiling it as often as possible, you will avoid writing pagefull's of code only to find a frustrating error that is hard to track down.

And, of course, you should visit your professor or TA's office hours! It makes TA's happy. :)

Good luck!


This also assumes that InvalidTestScore extends Exception or Throwable. Did you do that?

I'd write it more like this. Give it a look and see if you think it's simpler. Note that the Score class is more than just a container for your main method. Java's an object-oriented language. Try to start thinking about how to decompose your problems as objects:

package score;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

public class Score
{
    private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.##");

    private double grade;

    public Score(double grade) throws InvalidScoreException
    {
        if ((grade < 0.0) || (grade > 100.0))
            throw new InvalidScoreException(grade + " is invalid");

        this.grade = grade;
    }

    public double getGrade() { return this.grade; }

    public String toString()
    {
        return DEFAULT_FORMAT.format(this.grade);
    }

    public static void main(String[] args)
    {
        double sumOfScores = 0.0;
        List<Score> scores = new ArrayList<Score>();
        for (String arg : args)
        {
            try
            {
                double score = Double.valueOf(arg);
                scores.add(new Score(score));
                sumOfScores += score;
            }
            catch (InvalidScoreException e)
            {
                e.printStackTrace();
            }
        }
        if (scores.size() > 0)
        {
            System.out.println("Scores       : " + scores);
            System.out.println("Sum of scores: " + sumOfScores);
            System.out.println("# of scores  : " + scores.size());
            System.out.println("Average score: " + sumOfScores/scores.size());
        }
    }
}

class InvalidScoreException extends Exception
{
    public InvalidScoreException()
    {
        super();
    }

    public InvalidScoreException(String message)
    {
        super(message);
    }

    public InvalidScoreException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public InvalidScoreException(Throwable cause)
    {
        super(cause);
    }
}

If I run this code with the following command arguments:

-40 0 1 2 3 4 5 6 7 8 9 10

I get this result:

C:\JDKs\jdk1.6.0_21\bin\java -Didea.launcher.port=7536 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 102.216\bin" -Dfile.encoding=windows-1252 com.intellij.rt.execution.application.AppMain score.Score -40 0 1 2 3 4 5 6 7 8 9 10
score.InvalidScoreException: -40.0 is invalid
    at score.Score.<init>(Score.java:17)
Scores       : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    at score.Score.main(Score.java:38)
Sum of scores: 55.0
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
# of scores  : 11
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Average score: 5.0
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)

Process finished with exit code 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜