This is the task:
Display the usage message "Please input test scores with values between 0-100.
Enter 999 to finish."
Accept test scores within the range 0-100. If the number is out of range, display the message "Invalid Test Score", disregard that input and continue collecting values
Stop collecting test scores when the user inputs the number 999
Once all values have been entered, display the number of scores entered, the lowest score, the highest score, and the average.
Sample output for input: 57 -2 98 13 85 77 999
And this is my solution:
import java.util.Scanner;
public class TestScoreStatistics {
public static void main(String[] args)
{
int max=0;
int min=999;
int avg=0;
int count=0;
int sum=0;
int num;
Scanner scan=new Scanner(System.in);
System.out.println("Please input test scores with values between 0-100.\nEnter 999 to finish.");
num=scan.nextInt();
int temp=num;
do
{
if(num==999)
System.exit(0);
if(num>=0 && num<=100)
{
count++;
sum+=num;
if(num>max )
max=num;
if(num<min)
min=num;
}
} while((num=scan.nextInt())!=999);
System.out.println("Test Statistics:");
System.out.println("Number of tests: "+count);
System.out.println("Lowest: "+min);
System.out.println("Highest: "+max);;
System.out.printf("Average: " + sum/count);
}
}
but when input is 999 the output should be
Test Statistics:
Number of Tests: 0
Lowest: 0
Highest: 0
Average: 0
how do I do that?
This is what i would do. If it is as assigment for your programming classes, I would suggest replacing the lines with collections etc. with some other code (you can find that on stackoverflow)
List<Integer> scores = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Please input test scores with values between 0-100. Enter 999 to finish.");
int num = scan.nextInt();
do {
if (num == 999)
break;
if (num >= 0 && num <= 100) {
scores.add(num);
}
}
while ((num = scan.nextInt()) != 999);
if (scores.size() != 0) {
System.out.println("Test Statistics:");
System.out.println("Number of tests: " + scores.size());
System.out.println("Lowest: " + scores.indexOf(Collections.min(scores)));
System.out.println("Highest: " + scores.indexOf(Collections.max(scores)));
System.out.printf("Average: " + scores.stream().mapToInt(Integer::intValue).sum() / scores.size());
} else {
System.out.println("Test Statistics:");
System.out.println("Number of tests: 0");
System.out.println("Lowest: 0 *or write whatever you want here");
System.out.println("Highest: 0");
System.out.printf("Average: 0");
}
You might want to consider changing:
if(num==999)
System.exit(0);
to:
if(num==999)
break;
It will cause exiting do-while loop instead of finishing a program when your first input is "999". The problem you will need to solve then is dividing by 0 here:
System.out.printf("Average: " + sum/count);
You can change it to something like this:
if (count == 0) {
System.out.printf("Average: 0"); // Show average as 0 here, when count is equal to 0.
} else {
System.out.printf("Average: " + sum / count);
}
or something similar what you need to perform instead of dividing by 0 there.
Related
when i run this code and enter first grade 4 and second is 3 the count should be 2 and the avareg is 3
why the result do not be that?
public static void main (String args[]){
Scanner input = new Scanner (System.in);
System.out.println("enter your grade or -1 to exit ");
int grade = 0 , sum = 0 , count = 1;
while (count <= 5 && grade != -1) {
System.out.println("the grade no " + count);
grade = input.nextInt();
sum += grade;
count++;
}
System.out.println("the avareg is = " + sum/count);
System.out.println(sum);
System.out.println(count);
}
Count start at one and it should start at 0.
At first input, count become 2 and at second input it becomes 3.
I did the folowing changes and it works :
public class myClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter your grade or -1 to exit ");
int grade = 0 , sum = 0 ,count = 1 ;
for (; count<=5 && grade!=-1 ;count++) {
System.out.println("Enter " + count + ": ");
grade = input.nextInt();
sum = sum+grade ;
}
System.out.println("the avareg is = " + (sum+1)/(count-2));
System.out.println("sum= "+(sum+1));
System.out.println("count= "+(count-2));
}
}
I just add 1 to sum and taked 2 from count
Ok friends, I am trying to figure out why "-1" (my exit value) is compared and becomes my lowest grade and why "100" is not my highest grade. I'm sure they are simple reasons, but I don't see them.
sample input and output is the following:
Welcome to Grader-ator!
Enter a grade from 0 to 100, or enter a negative number to quit.
100
Enter a grade from 0 to 100, or enter a negative number to quit.
90
Enter a grade from 0 to 100, or enter a negative number to quit.
80
Enter a grade from 0 to 100, or enter a negative number to quit.
70
Enter a grade from 0 to 100, or enter a negative number to quit.
-1
Total sum of grades: 340
Total Number of Grades is: 4
Number of A's: 2
Number of B's: 1
Number of C's: 1
Number of D's: 0
Number of F's: 0
Highest Grade: 90
Lowest Grade: -1
Average Grade: 85.0
CODE STARTS HERE
import java.util.Scanner;
public class Lab7
{
/**
* author: Nate Fuller
* date: 9 Feb 17
* This program takes in any number of grades and performs some calculations
*/
public static int grade, totalNumOfGrades, totalSumOfGrades, highestGrade, lowestGrade,
numberOf_As, numberOf_Bs, numberOf_Cs, numberOf_Ds, numberOf_Fs,
oldGrade, newGrade;
public static double averageGrade;
static Scanner kb = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Welcome to Grader-ator!");
System.out.println("Enter a grade from 0 to 100, " +
"or enter a negative number to quit.");
totalSumOfGrades = 0;
grade = kb.nextInt();
while(grade >= 0)
{
System.out.println("Enter a grade from 0 to 100, " +
"or enter a negative number to quit.");
determineGrade();
}
printGrades();
}
public static void determineGrade()
{
//A
if(grade >= 90 && grade <= 100)
{
numberOf_As++;
increment();
compare();
}
//B
else if(grade >= 80 && grade <= 89)
{
numberOf_Bs++;
increment();
compare();
}
//C
else if(grade >= 70 && grade <= 79)
{
numberOf_Cs++;
increment();
compare();
}
//D
else if(grade >= 60 && grade <= 69)
{
numberOf_Ds++;
increment();
compare();
}
//F
else if(grade >= 0 && grade <= 59)
{
numberOf_Fs++;
increment();
compare();
}
else
{
System.out.println("Please enter a number between 0 and 100.");
grade = kb.nextInt();
}
}
public static void increment()
{
totalNumOfGrades++;
totalSumOfGrades += grade;
grade = kb.nextInt();
}
public static void compare()
{
newGrade = grade;
if(newGrade > oldGrade)
{
highestGrade = newGrade;
}
else if(newGrade <= oldGrade)
{
lowestGrade = newGrade;
}
oldGrade = newGrade;
}
public static void printGrades()
{
//Calculations
averageGrade = totalSumOfGrades/totalNumOfGrades;
System.out.println("Total sum of grades: " + totalSumOfGrades);
System.out.println("Total Number of Grades is: " + totalNumOfGrades);
System.out.println("Number of A's: " + numberOf_As);
System.out.println("Number of B's: " + numberOf_Bs);
System.out.println("Number of C's: " + numberOf_Cs);
System.out.println("Number of D's: " + numberOf_Ds);
System.out.println("Number of F's: " + numberOf_Fs);
System.out.println("Highest Grade: " + highestGrade);
System.out.println("Lowest Grade: " + lowestGrade);
System.out.println("Average Grade: " + averageGrade);
}
}
The whole if else block should be executed only if the newGrade is greater than equals 0. Added an if condition above all. This should solve the problem.
public static void compare()
{
if(newGrade >=0 ) {
newGrade = grade;
if(newGrade > oldGrade)
{
highestGrade = newGrade;
}
else if(newGrade <= oldGrade)
{
lowestGrade = newGrade;
}
oldGrade = newGrade;
}
}
To make your program work, remove the line grade = kb.nextInt(); from increment() method and last else block in determineGrade() method.
In your main method, make the following change:
grade = 0;
while(grade >= 0)
{
System.out.println("Enter a grade from 0 to 100, " +
"or enter a negative number to quit.");
grade = kb.nextInt();
determineGrade();
}
printGrades();
The reason why your code is not behaving accordingly is because before processing the input grade, you fetch the new input from the user and loose the old value which you needed for further processing.
import java.util.Scanner;
public class CashRegisterSimulation {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int total = 0 , num;
/*
* Create a program that will ask the user to enter a series of amounts.
* Assume that the user is allowed to enter positive numbers only. If the
* user entered a value of 0, the program will stop asking for numbers and
* should display the sum of the inputs given. Use DO WHILE Loops.
*/
do
{
System.out.print("Enter amount : ");
num = console.nextInt();
if(num <= 0)
{
System.out.println("STOP");
total = total + num;
System.out.println("The total amount is : " + total);
}
} while (num > 0);
}
}
How do I make my program add all the inputs the user entered after entering 0 or negative number?!
You want to add to the sum in each iteration for which num > 0:
do
{
System.out.print("Enter amount : ");
num = console.nextInt();
if(num > 0)
{
total = total + num;
}
} while (num > 0);
System.out.println("STOP");
System.out.println("The total amount is : " + total);
Move your total = total + num; inside an if condition and else print stop and the total. That should print the total if input is <=0.
do
{
System.out.print("Enter amount : ");
num = console.nextInt();
if(num>0)
total = total + num;
else
{
System.out.println("STOP");
System.out.println("The total amount is : " + total);
}
} while (num > 0);
this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html
Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
what ive got so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("i will add");
System.out.print("number: ");
int guess = keyboard.nextInt();
System.out.print("number: ");
int guess2 = keyboard.nextInt();
while(guess != 0 && guess2 != 0)
{
int sum = guess + guess2;
System.out.println("the total so far is " + sum);
System.out.print("number: ");
guess = keyboard.nextInt();
System.out.print("number: ");
guess2 = keyboard.nextInt();
System.out.println("the total so far is " + sum);
}
//System.out.println("the total so far is " + (guess + guess2));
}
Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.
Then after the loop output the user's sum.
I.e.:
int sum;
while(guess != 0)
{
guess = keyboard.nextInt();
sum += guess;
}
System.out.println("Total: " + sum");
Edit: also remove the guess2 variable, as you will no longer need it.
The code will be as below :
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int input = 0;
int total = 0;
System.out.println("Start entering the number");
while((input=keyboard.nextInt()) != 0)
{
total = input + total;
}
System.out.println("The program exist because 0 is entered and sum is "+total);
}
Programming by Doing :)
int x = 0;
int sum = 0;
System.out.println("I will add up the numbers you give me.");
System.out.print("Number: ");
x = keyboard.nextInt();
while (x != 0) {
sum = x + sum;
System.out.println("The total so far is " + sum + ".");
System.out.print("Number: ");
x = keyboard.nextInt();
}
System.out.println("\nThe total is " + sum + ".");
import java.util.Scanner;
public class AddingInLoop {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number, total = 0;
System.out.print("Enter a number\n> ");
number = keyboard.nextInt();
total += number;
while (number != 0) {
System.out.print("Enter another number\n> ");
number = keyboard.nextInt();
total += number;
}
System.out.println("The total is " + total + ".");
}
}
You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!
I'm trying to create this rather simple program for my java class. Everything is working, except for when I tried to have an input loop. I've never done that before, and it's ignoring every other input. Here is the problem prompt:
B. Ch. 4 – Average - Write a program that will read an unspecified number of integer grades and find the summary total and average. Print grades, total and average. The last record will be the trailer record of -1. Also output the final letter grade per syllabus grading scale.
And here is the code:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float counter = 0;
float accum = 0;
float addAccum = 0;
float tempLoop = 0;
System.out.println("Please Enter Grade, Enter -1 to Finish: ");
while (tempLoop != -1)
{
addAccum = in.nextFloat();
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat();
}
float avgGrade = accum / counter;
if(avgGrade >= 90)
{
System.out.println("\nYour Grade is: " + "A");
}else if(avgGrade >=80)
{
System.out.println("\nYour Grade is: " + "B");
}else if(avgGrade >=70)
{
System.out.println("\nYour Grade is: " + "C");
}else if(avgGrade >=60)
{
System.out.println("\nYour Grade is: " + "D");
}else
{
System.out.println("\nYour Grade is: " + "F");
}
System.out.println("\nGrade Total: " + accum);
System.out.println("\nCounter Num :" + counter); // for testing only
System.out.println("\nAverage Grade: " + avgGrade);
}
}
This is the console input/output:
Please Enter Grade, Enter -1 to Finish:
100
100
100
100
100
100
-1
-1
Your Grade is: C
Grade Total: 299.0
Counter Num :4.0
Average Grade: 74.75
You have in.nextFloat() twice in your while loop.
Change your logic to look for -1 first and then process the input.
Something like :
tempLoop = in.nextFloat();
while(tempLoop != -1){
sum += tempLoop;
tempLoop = in.nextFloat();
}
Hope this helps.
What you're doing is reading twice;
while (tempLoop != -1)
{
addAccum = in.nextFloat(); // Once Here
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat(); // Again Here
}
Thus only half of the data is being processed;
You'll need to read the first value before entering the loop, and then only read once at the end before checking that the new value is not -1
To avoid reading twice and reading inside the loop, or add ugly break statements, i would do it like this:
while ((addAccum = in.nextFloat()) != -1) {
counter++;
accum = addAccum + accum;
}