Skip to main content

stupid noob question with code attached fast responce needed

3 replies [Last post]
daren
Offline
Joined: 2009-03-09

ignore the comments with the //
im trying to get the sum of a user input array[]
the input works fine but the sum part always says the sum is 0
any help would greatly be appreciated.

import java.util.*;
import javax.swing.JOptionPane;
//create a class
public class prices {
public double Sum;
public double[] numbers;

public static void main(String[] args){

String Input;
double[] numbers; // An array for storing the input values.
int numCt; // The number of numbers saved in the array.
double num; // One of the numbers input by the user.

numbers = new double[4]; // Space for 5 doubles.
numCt = 0; // No numbers have been saved yet.

Input = JOptionPane.showInputDialog(null, "Please enter a price.");

while (numCt < numbers.length) { // Get the numbers and put them in the array.
Input = JOptionPane.showInputDialog(null, "Please enter a price.");
num = Double.parseDouble(Input);
if (num <= 0)
break;
numbers[numCt] = num;
numCt++;
}
prices aPrice = new prices();
double s;
s = aPrice.getSum();

//aveArray(numbers);
//highPrices();
JOptionPane.showMessageDialog(null,"The sum of the prices is " + s);
// JOptionPane.showMessageDialog(null,"ddd" + nag);
//}
System.exit(0);
}
public double getSum()
{
double[] numbers = new double[4];
double Sum = 0; // Start the total sum at 0.
for (int i=0; i

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
peter__lawrey
Offline
Joined: 2005-11-01

You are putting the input into "Input" and then ignoring it.
numbers will be full of zeros unless you set them to something so the sum will also be zero.

daren
Offline
Joined: 2009-03-09

while (numCt < numbers.length) { // Get the numbers and put them in the array.
Input = JOptionPane.showInputDialog(null, "Please enter a price.");
num = Double.parseDouble(Input);
if (num <= 0)
break;
numbers[numCt] = num;
numCt++;
}
prices aPrice = new prices();
double s;
s = aPrice.getSum();

//aveArray(numbers);
//highPrices();
JOptionPane.showMessageDialog(null,"The sum of the prices is " + s);
// JOptionPane.showMessageDialog(null,"ddd" + nag);
//}
System.exit(0);
}
public double getSum()
{
double[] numbers = new double[4];
double Sum= 0 ; // Start the total sum at 0.
for (int i=0; i Sum += numbers[i]; // Add the next element to the total

}
return Sum ;
}
public void setSum(double numbers)
{
Sum += numbers;
}

daren
Offline
Joined: 2009-03-09

can you see the entire code on one page?