Issue with do-while loop - java

Please note that I while I am comfortable with Java, I am not exceptionally gifted nor do I know all the jargon, so please explain your answers with very little coder jargon and as much normal English, or explain what the jargon means after you use it. Also, this is my first time with Stackoverflow, so let me know if this was a decent question and give me some pointers.
I am taking an AP Computer Science class at my high school. We use Java. We were recently taught do-while loops and I just completed the "lab" that uses do-while loops, however, there is an issue.
Firstly, let me explain the lab. The program generates a random integer between 1-10 which the user must guess (guess is stored as an int using a scanner), there are a few integer values which track number of guesses, how many guesses were greater than the computer integer, and how many were too low. When you look at my code, you will notice that I have a System.out.println(compGen);//compGen is the computer generated int. The purpose was to test the code.
The issue is in the if-statement that compares userGen (user guess) and compGen.
if(userGen==compGen)
{
//do a lot of stuff
}
In this if-statement, it is not printing the correct SOPs that I have written IF the user guesses more than once. HOWEVER, I did not write this into the program, it seems to do it on its own. I used the SOP I mentioned early where the compGen int is printed, and I typed that in as my first guess and it worked perfectly. Everything in the if-statement block executed perfectly and printed everything correctly. However, when I did it as my second guess, third guess, or any guess that was not the first one, NOTHING was printed. See code below and run it. I don't believe this should make a difference, but the IDE that I use is Eclipse, hence the package statement. Please help.
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
I haven't been able to figure out what is wrong. At one point I deleted the entire if-statement and re-typed it (I knew it wouldn't do anything, but I had to try). This issue makes no sense to me. There are no errors or anything that pop up, nothing pops up on the console which scares me a little. Thanks in advance.

First off, a lot of text you put here. Maybe try to minimize the problem next time as a suggestion ;) Otherwise everything is fine
To your problem. Let me minimize your code and then explain to you, what happens.
1. The Code
int val = scanner.nextInt();
do {
if (val < 5) {
// too low
val = scanner.nextInt();
} else if (val > 5) {
// too high
val = scanner.nextInt();
} else {
// correct
// THIS CODE DOESN'T RUN?!
}
} while (val != 5);
2. What does your code do?
You read your first number before your loop. That's fine. Then, you enter an if-elseif-else statement. Note, that once inside one of those blocks, the other blocks won't get executed. Now the problem is, that you read your next user inputs inside of the if-elseif! The program reads the next value and leaves the whole if-elseif-else. Your code does not execute, because the loop then ends before the next iteration, therefore the correct user input is not going through the if-elseif-else at all.
3. The solution
Remove all nextInt() reads and just have one as the first thing inside the loop:
int val;
do {
val = scanner.nextInt();
if (val < 5) {
// too low
} else if (val > 5) {
// too high
} else {
// correct
// THIS CODE RUNS NOW!
}
} while (val != 5);
Such things, structures that need to do something at least once before checking the loop condition, are usually done with do while loops rather than while loops

You are setting user input during the loop, and it is then checked afterwards. Try moving the body of the else if(userGen==compGen) block to after the loop like this:
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
}
while (userGen != compGen);//condition to be ultimately checked
//The numbers have matched since it exited the loop.
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}

The while condition is checked as soon as the program reaches the end of the code inside the loop. So suppose they enter the wrong number; the program says it's too low or too high, and then asks for another number:
userGen = userInput.nextInt();//new guess
Now suppose this new number is the correct one. The program finishes your if statement, then gets to the end of the loop. Then, at that point, userGen is equal to compGen. So the while condition fails, and the program exits the loop immediately, without ever getting to the code that prints the results.
One way to solve it would be to move the logic for userGen == compGen, that prints the results, outside the loop--that is, after the end of the loop. That way, it will be executed whenever the loop is exited. Note that when you exit the loop, we know that userGen == compGen, because if it weren't, the loop would go back.

Let's say the computer generated number was 3, and you guess 5.
5>3, so the if(userGen > compGen) statement executes:
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
you print the message, get a new guess, then increment your counter... but when you get the new guess, say it was the correct answer 3, userGen is now equal to CompGen (both are 3) and now the
while condition is evaluated:
while (userGen != compGen)
this is now false because userGen == compGen (both are 3). Your code never gets a chance
to print the correct message because the loop exits before it can happen. hope that helps

Your userGen is not being checked after every user input.
The problem is that you have your check inside an else-if block, which will check the end of the while statement before it loops back through again.
If you change
else if(userGen==compGen)
to
if(userGen==compGen)
then because it is not apart of the if-else block, it will be checked after every input (before the while condition is checked)
Alternatively you could move your user-input to the start of the do-while block like so:
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = -1;//USER GUESS
do
{
userGen = userInput.nextInt();
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
This will cause your if-else block to be checked everytime a user inputs data before the conditions for the do-while are checked.

Related

How to use while loop user input established variable out of scope (if possible)

I need to ask the user for a number of dice to roll, (at least 1) and then loop if necessary to return a positive integer. Simple question, but I'm new to Java and don't understand how to do this using a while loop and bringing my variable back into scope.
Here's what I have so far, as anyone can see my variable 'numOfDice' is never pulled back into scope, as I need it later in my program to establish a variable array length.
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
So as you can see my variable is never pulled back into scope, and I've tried initializing it before the while loop, with no luck. I've also tried
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
while (true) {
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
But this results in an infinite loop if a negative number is an input, as my if will repeat forever.
Anyways, I'm very new to Java (my 6th week learning) and any veteran help would be much appreciated. I'm willing to learn new ways to create these loops or tricks to pull variables back into scope (if possible).
Solved. Thanks to tgdavies telling me to split the declaration and assignment I was able to finish this problem. Here's the solution for anyone who stumbles upon this.
System.out.println("Hello! How many dice would you like to roll");
int numOfDice;
numOfDice = scan.nextInt();
while (true) {
if (numOfDice <= 0) {
System.out.println("Please enter a positive integer and try again");
numOfDice = scan.nextInt();
} else {
break;
}
}
This is very simple.
First you have to declare your variable outside the loop.
int numOfDice = -1;
Then you need to think of a way to update the state of your variable numOfDice inside the loop. Hence,
numOfDice = sc.nextInt();
Should be inside your loop. Now, the state of your variable numOfDice is updated. After that we can check if the value is a negative or not, and reiterate the loop accordingly.
Hence, the overall code will look like this.
int numOfDice = -1; //Declaration - value is negative because the while loop has to be executed at least once.
Scanner sc = new Scanner(System.in);
while(numOfDice<=0){ // checks if the variable is negative or positive, loop continues if the value is negative
System.out.println("Hello! How many dice would you like to roll");
numOfDice = sc.nextInt(); //updates the state of the variable
if (numOfDice<=0) {
// this line will be printed only if the value is negative.
System.out.println("Please enter a positive integer and try again");
}
}
Hope this answer is helpful.
Refer this article to understand more about while loops in java.
Let me start by showing my solution first...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
As you can see, it is not much of a variation, but it has clear boundaries. For example, you can't have a negative number of dice rolled. So checking for the number of dice to be less than zero (negative) is an error and an appropriate message is shown when that condition is reached.
The second thing you see is a clear case for ending the "forever" loop. And that is when zero is passed through the Scanner object. Not much of an explanation required. Pass zero and simply break out of the loop.
The rest, if a positive integer is passed, keep rolling the dice!
Output sample
Let's start rolling some dice
Hello! How many dice would you like to roll
2
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
9
Hello! How many dice would you like to roll
-3
Please enter a positive integer and try again
Hello! How many dice would you like to roll
-2
Please enter a positive integer and try again
Hello! How many dice would you like to roll
1
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
0
Goodbye!
...to return a positive integer
Sorry for the dramatic heading, but I miss this from the OPs question the first time I read it. The code above keeps rolling until the user enters zero. Let's modify this so that it returns a positive integer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
} else {
// Add some code here (i.e. a Random generation of dice values 1-6)
System.out.println("You rolled a " + diceRollValue);
break;
}
}
scan.close();
}
Variable Scope
Since the OP seems to struggle with issues related to scope, I will expand on this answer to focus on scope. Good coding practices call for minimizing the scope of variables. This means (in theory):
No global variables, period!
Local variables should be declared at the lowest possible block.
Variables shall be declared as close to the point of usage as possible.
Of course, in practice, global variables are often necessary. But what no developer should do is declare global variables by default. Instead, all variables shall be declared at the lowest levels of the code, and then "bubbled up" as needed and stop "bubbling" them up when the desired accessibility is reached. Let's look at an example from this code.
The variable numOfDice is declared inside the while loop. This is the lowest level where this variable can be declared. Since the variable is used at the top of the loop, it is OK to declare it and assign a value in the same line. The question is, should this variable be declared outside the loop? The answer is yes, for a very specific reason.
Creating a "forever" loop while(true){...} may not be a good idea. IN FACT, it can be argued that putting the break condition there might be a better coding practice than to include the break condition inside the loop. So, for this reason (and improving readability of the code as well), we might be better off setting the the variable outside the loop to a value, and then prompt the user to enter the number of rolls inside the loop like this:
System.out.println("Let's start rolling some dice");
int numOfDice = -1;
while (numOfDice != 0) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
}
Setting the value to -1 allows the instruction pointer to enter the loop because the evaluation of numOfDice returns true. Once inside the loop, it will continue to iterate until the evaluation returns false; and this is when the user enters 0. In the original code, negative values prompt an error message. Negative and positive values continue the "game". This is perfectly fine. As to the improved readability, when you see while (numOfDice != 0) the intent is clear; much better than to "hide" the break condition inside the loop. If the loop contain a lot of lines of code, the break condition is harder to find. So, in the end, this is a better solution.
An alternative is to use a do...while loop. This is the preferred structure when the intent is for the loop to run at least once. This is possible because the break condition is evaluated at the end of the loop rather than at the beginning in a conventional while loop. The equivalent do...while loop is as follows:
System.out.println("Let's start rolling some dice");
int numOfDice = 0; // initialize to the break condition value (just in case)
do {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
} while (numOfDice != 0);
The last thing with regards to scope. I mentioned before that variables should be declared as close to the point of usage as possible. This means that instead of this
public void myMethod() {
int myVariable = 0
.
.
.
.
.
myVariable = someCodeThatSetsValue();
.
.
}
You should do this instead to follow best practices
public void myMethod() {
.
.
.
.
.
.
int myVariable = someCodeThatSetsValue();
.
.
}

I need the input of the user to not skip the value 100

I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}

Java help regarding looping (do loops)

I'm trying to make a very basic game where you guess a number between 1-1000 using a do loop. Everything works, except when I finally make the correct guess, I am still prompted to make another guess, and when I enter the same correct guess again, the program terminates like it's suppose to.
Why do I have to make that extra guess to finally get my program to work? Am I looping around an extra time? Also, if I make a correct guess (the compiler will say I am correct then still prompt me), then a wrong guess (the compiler will tell me I'm wrong), then the correct guess again, the program will only terminate after I make the correct guess a second time.
The second do loop at the bottom is what I put in my main method. Everything above is in a method I wrote called play.
public static boolean play()
{
boolean c;
int n = 0;
do {
String input = JOptionPane.showInputDialog("Enter a number between 1-1000");
n = Integer.parseInt(input);
if (n == guess)
{
System.out.println("Correct");
c = true;
}
else if (n < guess)
{
System.out.println("Not Right");
c = false;
}
else
{
System.out.println("Not Right");
c = false;
}
guess++;
} while (c == false);
return c;
}
In main method:
do {
game1.play();
} while (game1.play() != true);
This loop runs the play method twice in each iteration of the loop :
do {
game1.play(); // first call
} while (game1.play()!=true); // second call
You are not testing the value returned by the first call, so even if it returns true, you would still call game1.play() again, which will display "Enter a number between 1-1000" again.
Replace it with:
boolean done = false;
do {
done = game1.play();
} while (!done);
This would only call play() one time in each iteration of the loop.
That said, I'm not sure why you need the outer loop.
You can just replace in with one call to game1.play(), since game1.play() will loop until the correct number is entered.

Couldnt find the Error in Guess Game Class

Okay, this is part of the full code of a guessing game.
public static void Game(){ //Second page of game with option of continue playing when guessed close enough to answer.
Scanner scan = new Scanner(System.in);
GuessingGame testgame=new GuessingGame();
testgame.Generator();
int num = testgame.GetGenNum();
//Produces a random number between 1 and 100 inclusive of 1 and 100
System.out.println("Guess the target integer which is between 1 and 100 inclusive");
int guess=scan.nextInt();
int difference=(guess-num);
while(guess!=num){
int yesCounter=0;
System.out.println("Guess again " +num+" "+difference);
guess=scan.nextInt();
difference=(guess-num);
///something wrong here, shouldnt repeat if difference too big
if(difference<=5||difference>=-5){ //something wrong with the condition, it says its close enough even tho it isnt.
while(yesCounter<1){
System.out.println("Close enough, do you want to keep Guessing? Y/N ");
yesCounter++;
String play = scan.nextLine();
//play=play1;
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
}
else{
Game(); ///TAKE note as it might restart the game with new random integer
}
}
}
}
}
}
output is:
.........................
Play? Y/N
y
Guess the target integer which is between 1 and 100 inclusive
50
Guess again 44 6
44
Close enough, do you want to keep Guessing? Y/N
Guess the target integer which is between 1 and 100 inclusive
..........................
the problem is, when user guess a number, the condition is if the difference between the guess and the generated number is 5 or smaller, tell user that its close enough, and ask if user wants to continue guessing, but the condition wasn't fulfilled and yet still runs, can someone help?
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
....
That isn't right, if((play.equalsIgnoreCase("y"))) can never be true, since the loop it is in, explicitely cannot be entered if it is true. That's where your problem is, it will always restart the game because it calls Game() in the else-branch. In short, this is what you do:
boolean _true = true;
while(! _true) {
if(_true) {
//impossible
}
else {
Game(); //ALWAYS
}
}
Since you tagged your question with homework, I will not give the full correction, but now you know where it goes wrong, you should be able to figure out what you need to change in order to advance :)
You mixed or and and (Note: The condition you used (difference<=5||difference>=-5) is always true.). You may use any of the following
if (difference<=5 && difference>=-5) { ... } # difference is 5 or less
or
if (difference<=-5 || difference>=5) { ... } # difference is 5 or more
Better readable if you use Math.abs(...) instead:
if (Math.abs(difference)<=5) { ... } # difference is 5 or less
and
if (Math.abs(difference)>=5) { ... } # difference is 5 or more
resp.
if(difference<=5||difference>=-5) This says if the difference is less than 5 or greater than -5. All numbers are less than 5 or greater than -5, so this is always true.
I'm assuming what you want is something like if(Math.abs(difference)<=5). This will tell you if the absolute value of your difference variable is less than or equal to 5.

Average of n numbers in java

Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.

Categories