how do i declare an array that accepts 5 doubles in which the user places the values into the array via input box.
how do i declare an array that accepts 5 doubles in which the user places the values into the array via input box.
public class TestScoresDemo {
public static void main(String[] args) {
// An array with test scores.
// Notice that element 3 contains an invalid score.
double[] badScores = {97.5, 66.7, 88.0, 101.0, 99.0 };
// Another array with test scores.
// All of these scores are good.
double[] goodScores = {97.5, 66.7, 88.0, 100.0, 99.0 };
// Create a TestScores object initialized with badScores.
try
{
TestScores tBad = new TestScores(badScores);
// The following statement should not execute.
System.out.println("The average of the bad scores is " +
tBad.getAverage());
}
catch (IllegalArgumentException e)
{
System.out.println("Invalid score found.\n" + e.getMessage());
}
// Create a TestScores object initialized with goodScores.
try
{
TestScores tGood = new TestScores(goodScores);
System.out.println("The average of the good scores is " +
tGood.getAverage());
}
catch (IllegalArgumentException e)
{
System.out.println("Invalid score found.\n" + e.getMessage());
}
}
}
Declare an array variable by specifying the type of data to be stored, followed by square brackets []
Code:dataType[] variableName;
- you can read the [] as the word "array"
To declare a variable for an array of integers:
Code:int[] nums;
- which you can read as "int array nums"
To declare a variable for an array of String objects:
Code:String[] names;
- which you can read as "String array names" - the array holds String references
You may also put the brackets after the variable name (as in C/C++), but that is less clearly related to how Java actually works
Code:int nums[]; // not recommended, but legal
Bookmarks