Golf score program? - java

So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.

You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;

You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;

You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.

while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.

Related

Close list with variables with the fixed number -1

I am very new to coding and Java. I have the following assignment: Write a program that reads a couple of positive numbers from the input and computes and prints the average, with 3 decimals precision. The input list closes with the number -1.
So I have a working program, however I have no clue how to integrate the condition 'print the average with 3 decimals precision'. Do you have any idea how to fix this? Many thanks!
See my code below:
import java.util.Scanner;
public class Parta {
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter -1 to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum == -1)
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
else
{
sum += negNum;
count++;
avg = sum/count;
}
}
}
}
You just have to break out of the loop for your -1 condition.
while(1) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n == -1)
break;
}
Change
for(int i=0; i < numbers.length + 1= -1 ; i++)
to
for(int i=0; i < n ; i++)
The
%n
is out of place in the print statement also. I'd remove that.
To implement your -1 condition, check for a == -1 in the for loop:
if (a == -1) {break;}
The input list closes with the number -1.
I assume this means that -1 is the final number you are looking for and when read then all inputs are then completed? You just need a condition to check if the number you are looking at is -1, if it is then stop reading.
Your code does not meet your requirements.
The first requirement is that you have to calculate fractions. But you stick to int as type of your variables. As written by #nbokmans your variables should be of type double or float.
The other problem is that your code takes the first number given as the count of the numbers to follow. But you're told to use any number for calculation until input is -1. You cannot do this with a for loop, you need a while loop for this.
An the easiest way to accomplish your task is to calculate the result on the fly while getting the input:
pseudo code:
declare sum as double initially 0.0;
while(input is not -1)
sum = (sum + input) / 2;
output sum:

Run loop an extra time if one of the inputs is bad

I have a for-loop which asks for scores between 0 and 10. It asks a certain amount depending on the number of judges.
Here's the code:
System.out.println("Number of judges: ");
int numOfJudges = IO.readInt();
int sum = 0;
for (int i=0; i<numOfJudges; i++) {
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
} else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
System.out.println(sum);
I want to make is so if a number is entered that's not between 0 and 10, it won't count that as one of the conditions as i < numOfJudges.
For example if I have 3 judges and I enter 2 wrong inputs, it will still only run the loop 3 times (and only take the good input into account) while I really want it to run 5 times to make up for the two incorrect inputs.
Increment numOfJudges in case of ELSE condition so that your FOR loop would run until you have desired number of correct inputs.
This is shortest and cleanest solution.
else {
System.out.println("Incorrect number, must be between 0 and 10.");
numOfJudges++;
}
You can use a while loop inside of the for-loop, instead of adjusting the for-loop:
for (int i=0; i<numOfJudges; i++) {
while(true){
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
break; //jump out of while-loop
}else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
}
System.out.println(sum);

How to Write a Summation of Fives in Java

I need to write a program in Java that can take the multiples of five up to a value given by the user, and then add all of the multiples together. I need to write it with a while loop.
Here's what I have so far:
import java.util.Scanner;
public class SummationOfFives {
public static void main(String[] args){
//variables
double limit;
int fives = 0;
//Scanner
System.out.println("Please input a positive integer as the end value: ");
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
limit = input.nextDouble();
//While Loop
while ((fives+5)<=limit)
{
fives = fives+5;
System.out.println("The summation is: "+fives);
}
}
}
When I run this program however, all it gives me is the multiples:
Please input a positive integer as the end value:
11
The summation is: 5
The summation is: 10
You're nearly there! Think about what your output is telling you. In your while loop, fives is the next multiple of 5 on each iteration. You're not adding it to a total variable anywhere.
So - define a total before the loop e.g.
int total = 0;
keep adding to it in the loop (where your System.out.println is now) e.g.
total = total + fives;
output the total after the loop e.g.
System.out.println(total);
I added a total variable into your loop that will accumulate the value of all of the summations.
int counter =1;
int total = 0;
//While Loop
while ((fives+5)<=limit)
{
total = counter*5;
counter++;
fives = fives+5;
System.out.println("The summation is: "+fives);
System.out.println("The total is: "+total);
}
The summation you do in fives is wrong. You need another variable multiple initialised to 0 that you will increment by 5 at each step of the loop. The stop condition in the while is (multiple < limit). Then fives are the sum of the multiples.
double limit;
int fives = 0;
int multiple = 0
//While Loop
while (multiple<=limit)
{
multiple += 5;
fives = fives + multiple;
System.out.println("So far, the summation is: "+fives);
}

Breaking out of a loop, so as to not include a value

I have a question about how to break out of a loop so as not to include a value. I am supposed to enter a few integer amounts to represent grades on a test and then break out of the loop when a value of "0" is entered. However I do not want 0 to be included in the calculation of the average and the minimum. That is a little vague so here is my code.
import java.util.*;
import java.lang.*;
public class Grades
{
public static void main (String[] args)
{
Scanner myScan= new Scanner(System.in);
String input="Input numerical grade:";
System.out.println(input);
int sum=0;
int count= 0;
int max= 0;
int min= 0;
double avg=0;
boolean notNull= true;
while(notNull== true)//While grades are greater than 0 ask the question again
{
int grade= myScan.nextInt();
if(grade==0)break;
if(grade>max)
{
max=grade;
}
if(grade<min)
{
min=grade;
}
System.out.println(input);
sum +=grade;
count++;
avg= (sum)/(count);
}
System.out.println("Maximum:"+max);
System.out.println("Minimum:"+min);
System.out.println("Average:"+avg);
}
}
And here is my return when I enter a few random test scores and 0. So instead of 0 I want my minimum to be 47.
----jGRASP exec: java Grades
Input numerical grade:
89
Input numerical grade:
47
Input numerical grade:
78
Input numerical grade:
0
Maximum:89
Minimum:0
Average:71.0
----jGRASP: operation complete.
You don-t take into account that you've initialized min with zero so:
if(grade<min)
{
min=grade;
}
will never change minbecause it is already minimal non-negative integer - zero.
So take this into account with following condition:
if(min == 0 || min < grade)
{
min=grade;
}
The 0 your program is printing out isn't the 0 the user enters. It's the 0 you initialize min to. (Currently, your average is being properly calculated.)
if(grade<min)
{
min=grade;
}
min's original value is 0. So unless you're taking negative grades, grade<min will never evaluate to true.
Instead of int min = 0;, you should do this:
int min = Integer.MAX_VALUE;
Also, as I commented, because you're never touching the boolean you use as the while loop conditional check, and you're only wanting to exit the loop when the user enters 0, you can just drop the entire variable, and use while(true).
It looks like you're already breaking out of your loop before processing the 0. The reason your minimum is 0 is because you initialized it to 0, and so of course if (grade<min) { min=grade; } will never happen for any positive grade.
You have a few options:
You could set min = max = grade directly for the first grade that is input.
You could initialize min to a large number that any reasonable grade would be less than, e.g. Integer.MAX_VALUE.
You have a few possibilities for an implementation of the first option. You could store some first flag that you initialize to true then set to false. You could maintain a count of the number of grades input and initialize min/max when the count is 0 (or 1 depending on how you do it). You could initialize min/max to some special flag values that a grade could never be, e.g. -1, and set them to grade directly when they equal that flag value.
The point here is that the reason you are seeing 0 for your minimum isn't because you're processing that final 0, it's because you initialize your minimum to 0, and no grade is lower than that.
You probably want somthing like this:
import java.util.Scanner;
public class Grades {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String input = "Input numerical grade:";
System.out.println(input);
int grade = myScan.nextInt();
int sum = 0;
int count = 0;
int max = grade;
int min = grade;
double avg = grade;
while (grade != 0) {
if (grade > max) {
max = grade;
}
if (grade < min) {
min = grade;
}
count++;
sum += grade;
avg = (sum) / (count);
System.out.println(input);
grade = myScan.nextInt();
}
System.out.println("Maximum:" + max);
System.out.println("Minimum:" + min);
System.out.println("Average:" + avg);
}
}
Puts out:
Input numerical grade:
89
Input numerical grade:
47
Input numerical grade:
78
Input numerical grade:
0
Maximum:89
Minimum:47
Average:71.0

How to calculate average test score

The homework problem is to write a program that adds together all the scores from a class exam and find the average.
I have two questions. To find the average, you have to divide the total score by the number of test takers. I don't know how to record how many test takers there are.
Does the method for getting the average go in the while loop or outside the while loop?
import acm.program.*;
public class AvgScore extends ConsoleProgram {
public void run(){
println("This program averages the test scores of an exam until the SENTINEL is entered .");
int total = 0;
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
}
println("the average for the class was");
}
private static final int SENTINEL = -1;
}
just add a count variable for every read
int count=0
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
count++;
}
the calculate the average
double avg = (double)total/count;

Categories

Resources