I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Statistics Program, assignment one, program
Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop,
enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
int amount = 0;
double totaladded = 0;
double userinput = 0;
userinput = keyboard.nextDouble();
while (userinput >= 0);
{
if(userinput > 0 )
{
totaladded = totaladded+userinput;
amount++;
}
}
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
}
use a do while loop instead,
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int amount = 0;
double totaladded = 0;
double userinput = 0;
do {
System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
userinput = keyboard.nextDouble();
if(userinput > 0 ) {
totaladded += userinput;
amount++;
}
} while (userinput >= 0);
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
Related
I'm very new to coding, and one of my projects was to create a program that uses a while loop to ask a user for test grades and find the average. The problem I have is that when it asks for the first grade, my instructor wants it to also print out "Enter -1 when you're finished" along with the first grade only. He wants the results to look something like this.
Test grade1? (Enter -1 when you are finished): random grade
Test grade2? random grade
Test Grade3? random grade
The average of your test grades is: average of all grades
Currently, I have the first grade as a separate line of code that asks the user and it is not in the loop. Is there any way to combine it into the loop and still have it to ask "Enter -1 when you're finished" but for only the first test grade?
P.s Sorry if my code is very messy I'm still not very good at it.
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Test grade 1? (Enter -1 when you're finished): ");
int grade1 = scan.nextInt();
int i = 2;
int testCounter = 1;
int sum = 0;
boolean flag = true;
while(flag) {
System.out.print("Test grade " + i + "? ");
int grades = scan.nextInt();
if (grades == -1){
flag = false;
break;
}
sum = grade1 + grades;
grade1 = sum;
i++;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double)sum/testCounter);
}
}
You can just check with an if statement whether it's the first test and display the additional message if that's the case.
Also you can get rid of the i variable and use testCounter in it's place. You also don't need the flag, just using break is enough.
At the end of the loop the testCounter will be off by one so you have to decrement by one when calculating the average ((testCounter - 1)).
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCounter = 1;
int sum = 0;
while (true) {
System.out.print("Test grade " + testCounter + "? ");
if (testCounter == 1)
System.out.print("(Enter -1 when you're finished): ");
int grade = scan.nextInt();
if (grade == -1) {
break;
}
sum += grade;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double) sum / (testCounter - 1));
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your salary per hour: ");
int salary = input.nextInt();
System.out.print("Enter number of hours: ");
int hours = input.nextInt();
int sum = salary * hours;
if (hours == 0) {
System.out.println("Stop!");
break;
}
System.out.println("Total salary " + sum);
}
}}
I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.
Your code does exactly what you tell it to do.
You tell it to:
first ask for TWO numbers
to then compare the first number, and stop on 0
So, the solution is:
ask for one number
compare the number, stop on 0
ask for the second number
If you want to exit whenever you type 0, then you have to check every value after its input.
There is the code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What's your salary per hour? ");
int salary = scanner.nextInt();
if (salary == 0)
exit();
System.out.print("How many hours did you worked today? ");
int hours = scanner.nextInt();
if (hours == 0)
exit();
int sum = salary * hours;
System.out.println("Your total salary is " + sum);
}
}
private static void exit() {
System.out.println("Have a nice day!");
System.exit(0);
}
Please write a comment if that doesn't match your expectation
The program asks to "write a Java program that will first ask the user how many grades they want to enter. Then use a do..while loop to populate an array of that size with grades entered by the user. Then sort the array. In a for loop read through that array, display the grades and total the grades. After the loop, calculate the average of those grades and display that average."
The output is the issue. No matter what I do with the code, it will only output two of the inputs I have typed. If I chose to enter 4,5, or 10 grades. It will only show the lowest two. Although the total and the averages are correct. What is it that I am missing here?
Here is what I have written:
import java.util.Scanner;
import java.util.Arrays;
public class TapCoGradeArray
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int count;
double inputGrade = 0;
double gradeTotal = 0;
double[] individualGrade;
System.out.println("Enter the number of students that are being graded.");
int numberOfGrades = keyboard.nextInt();
individualGrade = new double[numberOfGrades];
count = 0;
do
{
System.out.println("Enter the grade (from 0-100) for each student below.");
inputGrade = keyboard.nextDouble();
individualGrade[count] = inputGrade;
count++;
gradeTotal+= inputGrade;
} while(count < numberOfGrades);
Arrays.sort(individualGrade);
for(count = 0; count == individualGrade.length; count++);
{
// This next line is using gradeTotal as an array. However, there is no array by that name.
// Check which array this should be.
System.out.println("The grades entered are the following: \n" + inputGrade + "\n" + individualGrade[count]);
}
double gradeAverage = gradeTotal / numberOfGrades;
System.out.println("The total of the grades is " + gradeTotal);
System.out.println("The average of the grades entered is " + gradeAverage);
}
}
Two main problems
for(count = 0; count == individualGrade.length; count++);
this should not have a seimcolon and looping until this values is reached is correct.
for(count = 0; count < individualGrade.length; count++)
{
System.out.println("The grades entered are the following: \n" +
inputGrade + "\n" + individualGrade[count]);
}
My program accept input data from a user (up to 20 values) and calculate the average/find the distance from the average. If the user enters "9999" when no numbers have been added yet it will display an error message and tell the user to re-enter a value. Otherwise entering "9999" will collect what the user has entered and do its calculations. My program will have to collect all 20 inputs from the user and also ignore when the value "9999" is entered completely but, it will do the other calculations correctly. I'm not sure why its not recognizing my sentinel value whatsoever.
package labpack;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers = new double[20];
double sum = 0;
int sentValue = 9999;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the numbers you want up to 20");
do {
for (i = 0; i < numbers.length; i++) {
if (numbers[0] == sentValue){
System.out.println("Error: Please enter a number");
break;
}
else {
numbers[i] = input.nextDouble();
sum += numbers[i];
}
}
while (i<numbers.length && numbers[i]!=sentValue); //part of do-while loop
//calculate average and distance from average
double average = (sum / i);
System.out.println("This is your average:" + average);
for (i = 0; i < numbers.length; i++) { //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}
}
}
You can do this without doing the do-while and doing while instead.
if (numbers[0]== sentValue){
System.out.println("Error: Please enter a number");
break;
Here you are trying to compare the value without initializing the array with the user input.
This can be done in a much simple way :
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int i = 0;
double [] numbers =new double[10];
double sum =0;
double sentValue=9999;
int count = 0;
System.out.println(numbers.length);
System.out.print("Enter the numbers you want up to 20");
Scanner input = new Scanner(System.in);
while (i<numbers.length){
double temp = input.nextDouble();
if (temp >= sentValue){
if(i==0){
System.out.println("Error Message Here");
} else {
break;
}
}//if
else {
numbers[i] = temp;
sum += numbers[i];
i++;
count++;
}
} //part of while loop*/
//calculate average and distance from average
double average=(sum/i);
System.out.println("This is your average:" + average);
for (i=0;i < count;i++){ //Display for loop
double diffrence = (average-numbers[i]);
System.out.println("This is how far number " +numbers[i] +" is from the average:" + diffrence);
}//for loop
}//main bracket
}//class lab4 bracket
You need to store the value of the input.nextDouble() into a variable because when the compiler reads input.nextDouble(), each time it will ask the user for an input.
PS. You dont need to re-initialize this part :
java.util.Scanner input = new java.util.Scanner(System.in);
The above line can simply be written as :
Scanner input = new Scanner(System.in);
because you already imported Scanner.
import java.util.Scanner;
Hope this helps :)
I have like 3 hours trying to solve this simple problem. Here is what I am trying to accomplished: Ask the user to enter a number, and then add those numbers. If the users enters five numbers, then I should add five numbers.
Any help will be appreciated.
import java.util.Scanner;
public class loopingnumbersusingwhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input;
System.out.println("How Many Numbers You Want To Enter");
total = kb.nextInt();
while(input <= kb.nextInt())
{
input++;
System.out.println("How Many Numbers You Want To Enter" + input);
int input = kb.nextInt();
}
}
}
Your current code is trying to use input for too many purposes: The current number entered, the amount of numbers of entered, and is also trying to use total as both the sum of all numbers entered and the amount of numbers to be entered.
You'll want 4 separate variables to track these 4 separate values: how many numbers the user will entered, how many they entered so far, the current number they entered, and the total.
int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
int input = kb.nextInt(); // the current number inputted
total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum
Add this code after you take how many numbers the user wants to add:
int total;
for(int i = 0; i < input; i--)
{
System.out.println("Type number: " + i);
int input = kb.nextInt();
total += input;
}
To print this just say:
System.out.println(total);
import java.util.Scanner;
public class LoopingNumbersUsingWhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int input=0;
int total = 0;
System.out.println("How Many Numbers You Want To Enter");
int totalNumberOfInputs = kb.nextInt();
while(input < totalNumberOfInputs)
{
input++;
total += kb.nextInt();
}
System.out.println("Total: " +total);
}
}
You seem to be asking how many numbers twice.
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter");
int howMany = kb.nextInt();
int total = 0;
for (int i=1; i<=howMany; i++) {
System.out.println("Enter a number:");
total += kb.nextInt();
}
System.out.println("And the grand total is "+total);
}
What you should pay attention to:
name classes in CamelCase starting with a big letter
initialize total
don't initialize input twice
show an appropriate operand input request to your user
take care of your loop condition
don't use one variable for different purposes
which variable should hold your result?
how to do the actual calculation
Possible solution:
import java.util.Scanner;
public class LoopingNumbersUsingWhile {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter: ");
int total = kb.nextInt();
int input = 0;
int sum = 0;
while (input < total) {
input++;
System.out.println("Enter " + input + ". Operand: ");
sum += kb.nextInt();
}
System.out.println("The sum is " + sum + ".");
}
}