I have been set an assignment where I must find the average of a list of positive numbers enterd by the user, the amount of numbers entered is unknown. So far I have got the program to add all numbers that have been entered (the entry teminates when a user enters 0). I do not want the answer to this question on here because I am really trying to learn this fast!
I am having trouble with the while statement,
I wanted to say
WHILE ( numberentered = 0 );
......
but this doesnt seem to work
I originally did it like so:
while ( numberentered >= 1 );
System.out.print (numbersum);
but this still jumps out of the do loop when a negative number is entered.
Any idea guys.... If you understand my question but it is still worded very badly... please edit.
Thank you.
while (numberentered != 0) { < read new number and add it to total and ... (but you didn't want the answer...) > }
Shouldn't you be doing this?
while(numberEntered != 0) {
// add it up
}
It seems like maybe you meant to do:
while (numberentered != 0) {
//do stuff
}
Note that no semicolon is needed on the 'while' line itself.
This is what I interpreted the problem statement:
"User is allowed to enter the numbers as many times but when it enters 0, the program would display the average of the numbers being entered prior to 0 and exit"
You may go this way:
public static void main(String args[]) {
float no = 0;
float average = 0;
int count = 1;
if(args.length == 0) {
printf("No number being entered...program exits");
System.exit(0);
}
if(args[0] == 0) {
displayAverage(average);
return;
}
for(count;count<args.length;count++){
try {
no = Float.parseFloat(args[count]);
if(no == 0 ) {
break;
}
average = average + no;
}
catch(NumberFormatException nfe) {
printf("Please enter only numbers");
}
}
average = average/count;
printAverage(average);
}
private void displayAverage(float average){
System.out.println("average is: "+ average);
}
hope this may helps..
Related
I am a beginner and as you can see I made a simple Java game.
The user has 5 tries to guess a number between 1 and 20.
If the user wins a congratulations message will show.
If the user didn't succeed a game over message will pop up.
Issue
When the user enters the right answer on the 5th try both congratulations and game over messages will pop up.
Code
package org.meicode.Loops;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome");
System.out.println("Enter your name please ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.println("Hello " + name);
System.out.println("Type 1 to start the game");
int yes = scanner.nextInt();
while (yes != 1) {
System.out.println("Type 1 to start the game");
yes = scanner.nextInt();
}
System.out.println("Guess the number in my mind,It is between 1 and 20 and you got 5 tries");
int timestried = 0;
Random random = new Random();
int x = random.nextInt(20) + 1;
while (timestried < 5) {
timestried++;
Scanner scanner1 = new Scanner(System.in);
int answer = scanner.nextInt();
if (x == answer) {
System.out.println("Well done, you did it");
} else if (x > answer) {
System.out.println("Try again,hint:the value is bigger than what you typed");
} else if (x < answer) {
System.out.println("Try again,hint:the value is smaller than what you typed");
}
}
System.out.println("Game over, the number was " + x);
}
}
How can I fix it?
Here is my attempt. I have added some comments in the code to help you.
Note that I have changed some of the file names to, so you may need to change them back for it to run, or just copy the main code section:
package com.misc;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
public class GameTest {
public static void main(String[] args) {
System.out.println("Welcome");
System.out.println("Enter your name please ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.println("Hello " + name);
System.out.println("Type 1 to start the game");
int yes = scanner.nextInt();
//We initialize the answer variable here to use it later on.
int answer = 0;
while (yes != 1) {
System.out.println("Type 1 to start the game");
yes = scanner.nextInt();
}
System.out.println("Guess the number in my mind,It is between 1 and 20 and you got 5 tries");
int timestried = 0;
Random random = new Random();
int x = random.nextInt(20) + 1;
//Print out the randomly generated number so we can test it. We answer wrong 4 times then put in the right answer to see if the message is fixed.
System.out.println("Testing: the answer is " + x);
while (timestried < 5) {
timestried++;
Scanner scanner1 = new Scanner(System.in);
answer = scanner.nextInt();
if (x == answer) {
System.out.println("Well done, you did it");
} else if (x > answer) {
System.out.println("Try again,hint:the value is bigger than what you typed");
} else if (x < answer) {
System.out.println("Try again,hint:the value is smaller than what you typed");
}
}
//This is the conditional that uses the answer variable we declared earlier above to avoid printing out the Game Over message in a success scenario.
if (x != answer) {
System.out.println("Game over, the number was " + x);
}
}
}
Here is proof that it works. I made the program print out the real answer, answered wrong 4 times and correctly the 5th time.
Simple fix
There are 2 things I would add to your code to achieve the desired behavior:
break or exit the loop on correct answer
set a flag signaling the question was solved to later build the message upon it
Basics: How to break loops and why
You can achieve this by two ways:
break the loop when the user typed the correct answer
add an exit-condition to the loop
return from the whole method prematurely
throw an exception that can either be caught outside or will also exit the method
I will explain (1) and (2) here in this answer (3) in a separate answer.
(1) Breaking the loop
The loop shall continue until:
the maximum number of tries has been reached
the correct answer was given
Use a break; statement to break the loop if correct answer:
if (x == answer) {
System.out.println("Well done, you did it");
break;
}
Note: contrary a continue; will skip further loop-body and jump to the next iteration.
(2) add a flag signaling premature exit (e.g. correct answer)
You can add a flag that is set to true if the user types the correct answer:
boolean userHasAnsweredCorrect = false;
while (timesTried < 5) { // here the flag can be added instead breaking
if (x == answer) {
System.out.println("Well done, you did it");
userHasAnsweredCorrect = true;
break;
}
}
// omitted some lines .. then at the end
if (userHasAnsweredCorrect) {
System.out.println("You beat the game!")
} else {
System.out.println("Game over, the number was " + x);
}
See how you define the flag before the loop, set it inside the loop (together with a break;) and then test on the flag after the loop.
Combined: set flag and add exit-condition
boolean userHasAnsweredCorrect = false;
while (timesTried < 5 && !userHasAnsweredCorrect) { // here the break happens instead
if (x == answer) {
System.out.println("Well done, you did it");
userHasAnsweredCorrect = true;
// break;
}
}
Find 2 more simpler ways of breaking the loop in my other answer, here follows the 3rd way:
Put the whole game into a method like startGame() and exit from that. Either exit after loop with max-tries has finished or inside the loop (prematurely) if answered guess was correct.
(3) Exiting the loop and method using return
That premature method-exit can be achieved by inserting a return; inside the loop.
public void startGame() {
// rest of preparation
// starting the game-loop
for (int i = 1; i <= maxTries; i++) { // for-i is indexed and safer (no infinite-loop)
// read input
// score or evaluate answer against x
if (x == answer) {
System.out.println("Well done, you did it");
return; // exit the method, not reaching "game-over" after the loop
}
// continue the iteration
}
// game-over (if not previously exited because of victory)
}
To have an exit-condition for the for loop, define int maxTries = 5 either as local variable, class field or constant.
Problem to solve
Write a program called MyWhiley1 that asks the user to type a
positive integer.
When the user types a negative value the program writes ERROR and
asks for another value.
When the user types 0 that means that the last value has been typed
and the program must write the average of the positive integers.
If the number of typed values is zero the program writes 'NO
AVERAGE'.
But I have some errors my code does not run properly if I type a positive number and then a negative number nothing happens.
public class MyWhiley1 {
public static void main(String[] arg) {
int sum = 0, list = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Type a postive integer if you enter zero the list is compelete");
int number = reader.nextInt();
do {
if (number > 0) {
sum += number;
list++;
} else if (number < 0) {
System.out.println("ERROR type in a postive integer");
}
reader.close();
} while (number != 0);
if (list != 0) {
System.out.println("Average is: " + sum / list);
} else
System.out.println("NO average");
}
}
You have two issues, you are not reading the number within loop and you are closing the reader while being within loop:
int number = 0;
do
{
number = reader.nextInt();
if (number>0)
{
sum+=number;
list++;
}
else if (number<0)
{
System.out.println("ERROR type in a postive integer");
}
}while (number!=0);
reader.close();
What it looks like is happening here is that you accidentally put the reader.close() call inside the while-loop, so the Scanner is closed after the first iteration of the loop, regardless of what happens. Try putting reader.close immediately after the end of the while-loop; that should fix the issue.
Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!
I'm doing an assignment for school that requires us to find the largest of ten numbers. The numbers are between 0-9. I believe I got that part down. My problem is I'm trying to add an extra feature that is not required for the assignment. I am trying to get the loop to completely restart after the boolean statement is false and gives an error message. After I type the invalid value in, it gives the error message, but after I press "ok" it continues on to the next number. I want it to start back at the beginning of the loop.
Here's the code:
package Largest;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LargestMain {
public static void main(String[] args) {
int number = 0;
String numStr = "";
int []myArray = new int[10];
int count = 1;
int largest = 0;
boolean valid = false;
while(valid == true); { // Loop to check validity
for(int i = 0; i < myArray.length; i++) {
myArray[i] = i + 1;
numStr = JOptionPane.showInputDialog("Please enter number " + count++ + ":");
number = Integer.parseInt(numStr); // Converts string value to integer
if(number >= largest) {
largest = number;
}
// If-Else if statements checks if values entered are equal to 0-9
if(number >= 0 && number <= 9) {
valid = true;
}
else if ((!(number >= 0 && number <= 9))) {
valid = false;
}
if (valid == false) {
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
continue;
}
}
JOptionPane.showMessageDialog(null, "The Largest Number Is: " + largest, "Results", JOptionPane.PLAIN_MESSAGE);
}
}
}
I could just end the loop here by adding return:
if (valid == false) {
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
return;
}
I just really want to learn how to restart the loop from the beginning. I tried search different topics, but none helped me solve my problem. Thanks for the help in advance!
To restart a loop, you would use the continue keyword. continue will skip to the next loop iteration.
When using a while loop, it'll simply restart the loop, since the loop doesn't end til valid is true. When using a for loop, itll skip to the next iteration (so if you're currently on index 5 and use continue, it'll move onto index 6 instead of staying at 5).
For nested loops, you can label the loop to specify which loop the statement is for:
firstloop:
while(valid) {
secondloop:
while(true) {
continue firstloop;
}
}
Also, no need for == true when checking a boolean. It could be represented as
while(valid) {
}
As for checking for false, valid == false, you'd use
while(!valid) {
}
Since you're a beginner and trying to learn, I have done a review of your code and enclosed some comments that might help you. I have posted updated code below.
Declarations: You should declare a variable in the innermost closure that requires it. Except largest, all other can go inside the for.
Your array variable did not make sense to have. Since you're keeping track of the largest as you go and not finding it at the end.
Control: Your /loop to check validity/ needs to be strictly around the input part, not your whole program, so you can repeat just the input statements till you're satisfied.
public static void main(String[] args)
{
int largest = 0;
for(int i = 1; i <= 10; i++)
{
boolean valid = false;
while (!valid)
{
String numStr = JOptionPane.showInputDialog("Please enter number " + i + ":");
int number = Integer.parseInt(numStr); //Converts string value to integer
if (number >= 0 && number <= 9)
{
valid = true;
}
else
{
JOptionPane.showMessageDialog(null, "INVALID INPUT...Try Again!!!", "Results", JOptionPane.YES_OPTION);
}
}
if (number > largest)
{
largest = number;
}
}
JOptionPane.showMessageDialog(null, "The Largest Number Is: " + largest, "Results", JOptionPane.PLAIN_MESSAGE);
}
You can use a labeled continue:
firstloop:
while(valid){
secondloop:
for(int i=0; i<10; i++{
//something
if(something){
continue firstloop;
}
}
}
See the documentation for more details.
UPDATE: Also... there is no need for the condition in the else part of your if/else statement. Just doing a else{ valid=false } would be equivalent to what you're doing right now. Another option would be to simplify it even further and skip the if/else part alltogether and just have:
valid = number >= 0 && number <= 9
Write a recursive function, that is, a function that calls itself.
public static void DoSomething()
{
// optionally ask the user for input at this point before processing begins.
while(yourCondition)
{
// do your stuff.
}
// when execution reaches here the condition is no longer valid; start over.
if(conditionToStartOver)
DoSomething(); // start again
}
Your logic is almost right but you shouldn't be looping on valid in the outer loop. Remember, you want to stop the inner loop when an input is invalid. Normally the outer loop would give the user an option to exit the program.
So for example:
while(true) {
boolean valid = true;
for(...; ...; ...) {
...
if(number < 0 || 9 < number) {
valid = false;
break;
}
}
if(valid) {
// show largest input dialog
} else {
// show invalid input dialog
}
// optionally ask the user if they want to exit
// if so, break
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a new bee in java ... so I have an assignment and I am stuck can somebody help me
I have to write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zero's). The program should end when the user inputs 0.
Sample run:
Enter an int value (the program exits if the input is 0: 1 3 -1 2 0
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
The thing which i wrote is ... The logic seems right but it does not work ...
The code that I wrote is
public class AverageNumbers {
public static void main(String[] args)
{
int data = 0;
int positive = 0;
int negative = 0;
int count = 0;
while (data !=0)
{
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
if (data < 0 || data > 0){
count++;
if (data >0)
positive++;
else if (0<data)
negative++;
count = count + data;
count++;
}
String strOutput = "The number of positives is " + positive;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of negatives is " + negative;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of total is " + count ;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of average is " + count/data ;
JOptionPane.showMessageDialog(null, strOutput);
}
}
In your while loop condition, you're checking if data !=0 which returns false and the while loop code block doesn't execute, because the data is set to int data = 0; at the beginning of program.
There are 2 simple solutions to your problem:
Set data to something other than 0
Use do...while loop, see example below
int data = 0;
...
do{
...
} while (data != 0);
Two errors here:
Your loop will never execute, since on the initial run, data == 0. You can fix this by asking the question early as opposed to later:
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
int data = Integer.parseInt(strdata);
Then, later in the loop (towards the bottom):
strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
Even if you were able to enter the loop, you'd get all positive number counts and no negative number counts. The reason for this: data > 0 and 0 < data are equivalent boolean statements.
What you probably meant was this:
if (data > 0) {
positive++;
} else if (data < 0) {
negative++;
}
As others have said, initializing data to is a problem, but see below for my advice there.
The other issue you're going to run into is you're having count do too much.
Assume count starts at 0 and the user enters 3.
In
if (data < 0 || data > 0){
count++;
You're now at one, the you go into
count = count + data;
count++;
And count goes up to 4, then ++ up to 5.
Even if you've got a 0 entered, you still alter count before breaking the loop.
Try something like Orel mentioned with having a sum int that just keeps track of the sum. Keep count only to count, and only the count++ at the very bottom, completely erase
if (data < 0 || data > 0){
count++;
Instead, try something like this for the 0 check to prevent screwing with the whole thing:
while(true){
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
if (data == 0)
break;
...
}
You could use a do/while here as well. This will allow you to initialize data to whatever (or nothing) that you like. Another thing, make sure that they value they enter is not null and is an int, your professor will definitely enter "sleirjwlfie" when prompted for a number because it's best practice to assume the user will break your program. So something in pseudo-code like:
while(true){
// get value from user
// if value is null OR value is not an int
continue;
}
I'll let you sort out the how to there as to not kill the learning experience, but I know that kind of thing bit me in school more than once.
Good luck!
+1 for attempting and writing almost working code :)
As others have pointed out your code has few bugs which needs to be fixed.
Your assignment to data should happen at least once before entering
while(data) loop.
You don't need to check value of input before incrementing count, if
it's 0 then you won't enter loop. Otherwise you will have to
increment count anyways.
For calculating total and average you need to use one more variable
Are you using any IDE ?
Use IDE (Eclipse is one of the best one) and debug your code step by step to check what's happening.
Google for how to use IDE and debug.
Below is working code for your reference.
import javax.swing.*;
public class AverageNumbers {
public static void main(String[] args)
{
int data = 0;
int positive = 0;
int negative = 0;
int count = 0;
int total = 0;
double avg = 0;
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
while (data !=0)
{
if (data >0) {
positive++;
} else {
negative++;
}
total = total + data;
count++;
strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
}
String strOutput = "The number of positives is " + positive;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of negatives is " + negative;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of total is " + count ;
JOptionPane.showMessageDialog(null, strOutput);
avg = total * 1.0 /count ;
strOutput = "The number of average is " + avg;
JOptionPane.showMessageDialog(null, strOutput);
System.exit(0);
}
}
Well, the first problem is here. You initialize data to 0:
int data = 0;
Then your loop condition checks for data != 0 :
while (data !=0) {
...
}
Since data is assigned 0, the loop is never entered.
You should add a 'sum' int variable and change this line
count = count + data;
With this
sum += data;
Also change your while-loop to do-while loop.