简体   繁体   中英

Method within a while loop

Specifically, in the while loop there is some logic area that is not allowing the program to flow correctly. I have walked through this loop and it should work. Some of the errors I am having is when I enter "0" it doesn't exit right away, other words I have to press 0 twice which doesn't make sense to me unless I am not comprehending the while loop correctly. The other error is in my add () method, what ever I enter it only tells me the first number I inputted. So I am fairly certain the error is in my loop, but I can't see where the logic error is coming from. Any help would be appreciated, thank you.

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    
            input();
            numb = input();
            //Method to find the sum of all the numbers inputed
            sum(add,numb); 
            add = sum(add,numb); 
            //Used to find the average of all the numbers entered (sum / count)
        }//End for loop
        avg(add,count);
        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

This is something that I dont think you want:

        //Call Input method    
        input();
        numb = input();

Doing it twice results in asking for a number twice - but only using the second...

Also, be very careful about floating point numbers and equality. 0 is a good number, but other numbers, especially fractions are not so obvious...

Other than that, the code seems OK...

(and you don't have an "add" method)

You ask for input and then throw it away

//in the initialization you do:...
float numb = input();//used to store the value of Input() method
//and in the loop you do it again, overwrite the first input
numb = input();

You should only declare the numb in the preamble and leave the rest to the loop.

Problems in the loop

Looking at your loop I see the following problems:

while (numb != 0) {//Begin for loop
    count += 1;
    //Call Input method    
    input();                  <<-- 1. should be removed, input goes nowhere 
    numb = input();
    //Method to find the sum of all the numbers inputed
    sum(add,numb);            <<-- 2. should be removed, output goes nowhere
    add = sum(add,numb); 
    //Used to find the average of all the numbers entered (sum / count)
}//End for loop
avg(add,count);               <<-- 3. why do you keep repeating??
average = avg(add,count);//used to store the average of the numbers

Whilst java allows you to call functions (return a value) as if they're procedures (returns nothing aka void ), you should only do this if you're not interested in the return value.
In this case you're calling the function twice.
The first call asks the user for input and then throws the result away, the second call ask the user again and then stores the answer.

Because you are running in a loop, it's hard to differentiate the duplication from the loop running twice.
You should never have to call a function twice, like you're doing in your loop.

You don't have to pre-announce your functions
Just state what you want to happen and java will do it.

Other issues
In this case it's not a problem, because numb is directly inputted by the user. But in general you should never compare a float against an absolute value.
The following is not guaranteed to be true.

((a/b*b)-a == 0)

Because of rounding errors you can get unexpected results, where the outcome is of ((a/b*b)-a) is 0.00000000001 which will cause you test (numb != 0) to fail.
Because you're comparing against user input it's fine for now, but if you're checking the output of a calculation, remember that floating point calculations are inexact!

From what I am seeing, you should only call "input()" once in your loop. You are calling it twice - ie

          input(); 
          numb = input();

Take out the first "input();" and you should be good to go.

You also don't need to execute "sum(add,numb);" twice, so take out the "sum(add,numb);" line and just use "add = sum(add,numb);".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM