好的,所以我只是问了有关循环内方法的问题。好吧,我得到了大部分答案;但是,我的 sum() 方法仍然不起作用。例如,我将 5 放在数字 3 次,这三个数字的总和应该是 15。所以在整个循环中的某个地方,一个数字不会被添加到变量 add 中。任何帮助将不胜感激,谢谢。
// File: RandyGilmanP2.java
// Author: Randy L. Gilman
// Date: 10/5/2013
// Purpose: Design and implement a Java program that will gather a group of
// floating point numbers and determine the sum and average of the
// data entered. The program should use separate methods for inputting
// the data, calculating the sum, calculating the average, and
// displaying the results. A sentinel value should be used to indicate
// the user has completed entering their numbers. The output should
// display a message that includes the count of the numbers entered,
// the sum of the numbers and the average of the numbers. If the sum
// of the numbers is greater than 100, a warning message should be
// displayed indicating “values have exceeded a sum 100”.
import javax.swing.JOptionPane;
public class RandyGilmanP2 {//Begin class
public static void main(String[] args) {//Begin main
JOptionPane.showMessageDialog(null, "Hello Welcome to Sum and Average"
+ "\n of a Number Calculator Program"
+ "\n By: Randy Gilman");
//Declare variables
float add = 0;//used to store the sum of the numbers inputed
float numb = input();//used to store the value of Input() method
float average;
int count = 0;// Used as a counter variable
//Loop that will be controlled by a sentenil value
while (numb != 0) {//Begin for loop
count += 1;
//Call Input method
numb = input();
//Method to find the sum of all the numbers inputed
add = sum(add,numb);
//Used to find the average of all the numbers entered (sum / count)
}//End for loop
average = avg(add,count);//used to store the average of the numbers
results(count,add,average);
}//End Main
public static float input(){//Begin Method
//Will keep gathering input from user until input is equal to 0
String NumberString = JOptionPane.showInputDialog("Enter a floating point number"
+ " (The program ends when 0 is entered):");
//Convert string to float
float number = Float.parseFloat(NumberString);
return number;
}//End Method
public static float sum(float sum, float numb2){//Begin method
//Add number to the previous number to compute total
sum += numb2;
if (sum > 100)
JOptionPane.showMessageDialog(null, "***WARNING***" + "\n"
+ " The sum of your numbers exceed 100");
return sum;
}//End Method
public static float avg(float num1, float num2){
//Declare variables
float result;
//Preform calculation of average
result = num1 / num2;
return result;
}//End Method
public static void results(int counter, float addition, float aver){//Begin method
//Declare variables
JOptionPane.showMessageDialog(null,"The total amount of numbers you entered are: " + counter);
JOptionPane.showMessageDialog(null,"The sum of the numbers you have entered is: " + addition);
JOptionPane.showMessageDialog(null,"The average of the numbers you have entered is: " + aver);
}//End Method
}//End Class