0

The function reads numbers from the user, summing them up in the process until the user enters the string "end". It then stops input & displays the avg of the numbers.

void mean() {
int mean1,f1=0,c1=0,g1;
boolean k1;
String end=null;
System.out.println("Enter numbers");
while(k1=false)
{
    end=input.nextLine();
    if(isNumeric(end)==true)
    {
        g1=Integer.parseInt(end);
        f1=f1+g1;
        c1=c1+1;
    }
    else if(end=="end")
    {
        k1=true;
    }
}
mean1=f1/c1;
System.out.println("The mean is: "+mean1);
}

However I am unable to escape the loop no matter what, even when the user enters "end".

Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 1
    I rolled back the question. You edited a critical part (i.e. the `String`-comparison via `==`), rendering already existing answers invalid. – Turing85 Apr 03 '21 at 09:24

2 Answers2

2

you're using the assignment operator inside the while condition
use == instead and initialize the k1 as false.

void mean() {
int mean1,f1=0,c1=0,g1;
boolean k1 = false;
String end=null;
System.out.println("Enter numbers");
while(k1==false)
{
    end=input.nextLine();
    if(isNumeric(end)==true)
    {
        g1=Integer.parseInt(end);
        f1=f1+g1;
        c1=c1+1;
    }
    else if(end.equals("end"))
    {
        k1=true;
    }
}
mean1=f1/c1;
System.out.println("The mean is: "+mean1);
}
Riven
  • 375
  • 2
  • 11
0

Inside the while loop you are using while(k1=false), which is an assignment operator. To compare values you need to use ==. The while(k1=false) would set k1 to false for each iteration. Since initialization statement returns the initialized variable itself, such a condition would always return true. This would make the statement k1=true inside the else if to be useless.

Also, string comparisons should be done using the equals method.

Since the k1 variable is boolean, it is enough to use while(!k1) instead of using while(k1 == false).

Also, please note that it is always better to give meaningful names to variables. I would suggest you to rename the variable k1 to something more meaningful like hasMoreInput.

Also, rather than initializing it to false, initialize it to true and change it to false whenever there are no more inputs from the user.

boolean hasMoreInput = true;
while (hasMoreInput) { // more readable than while (!k1)
    // rest of the code.
    else if(end.equals("end")) {
        hasMoreInput = false;
    }    
}
Gautham M
  • 4,816
  • 3
  • 15
  • 37