Daimeon Daimeon - 1 month ago 9
Java Question

Return Values from methods

I need help to figure out what i'm missing. I've gone though the code and I don't understand why I am getting this error. I new to java and mistakes do tend to happen when learning the syntax please help me fix this return from method.

import javax.swing.JOptionPane;

public class TestScores {


public static void main(String[] args)
{
int[] testScores;
testScores = getTestScores();
getAverage(testScores);
double average;


average = getAverage(); //*method getAverage in class TestScores cannot be
*applied to given types;
*required: int[]
*found: no arguments
*reason: actual and formal argument lists differ
*/in length

displayScores(average);

System.out.println(testScores[0]);
System.out.println(testScores[1]);
System.out.println(testScores[2]);
}
public static int[] getTestScores()
{
int[] scores = new int[3];


for (int testValues = 0; testValues < scores.length; testValues++)
{
String input;

input =
JOptionPane.showInputDialog("What is the test score for number " + (testValues + 1) + " ? ");


while (input.isEmpty())
{
input = JOptionPane.showInputDialog("Nothing was enterd for test " + (testValues + 1) + " please enter a value.");
}

scores[testValues] = Integer.parseInt(input);


while (scores[testValues] <= 0 || scores[testValues] > 100)
{
input =
JOptionPane.showInputDialog("The number " + scores[testValues] + " for test " + (testValues + 1) + " is invalid."
+ " Please enter a number in the range of 1 though 100");

scores[testValues] = Integer.parseInt(input);
}
}

return scores;

}

public static int[] getAverage(int[] input)
{
for (int avg = 0; avg < input.length; avg++)
{
int total;
double result;

total = input[avg];
result = total / input.length;
}
return result; //cannot find symbol
*symbol: variable result
*/location: class TestScores
}

public static void displayScores(double average)
{
JOptionPane.showMessageDialog(null, "The average is " + average + ".");

if (average <= 100 || average >= 90)
{
JOptionPane.showMessageDialog(null, "The letter grade is A.");
}
else if (average < 90 || average <= 80)
{

JOptionPane.showMessageDialog(null, "The letter grade is B.");
}
else if (average < 80 || average <= 70)
{

JOptionPane.showMessageDialog(null, "The letter grade is C.");
}
else if (average < 70 || average <= 60)
{

JOptionPane.showMessageDialog(null, "The letter grade is D.");
}
}
}

Answer

Out of scope

{
   double result;
   …
}
return result; //cannot find symbol

You define the variable inside the curly braces. Those braces define a block of code. That block has scope. After the closing curly brace, any variables defined within are gone (all references dropped, become candidates for garbage collection). When you say return result, there is no result.

Move that definition outside the braces.

double result;
{
   result = …
   …
}
return result; //cannot find symbol

See: Java, What do curly braces mean by themselves?