Hi Im new to java and trying to do some exercises to familiarize myself with it. I am trying to calculate the sum and average of the user input numbers using a for each or enhanced for loop. What i have done is to store the numbers in an array. Can you please check if my code is correct.
Scanner scanner = new Scanner(System.in);
double inputNum;
double sum= 0;
int counter;
System.out.println("How many entries would you like input");
int entry = scanner.nextInt();
for (counter = 0; counter< entry; counter++){
double [] numbers = new double[entry];
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
for (double x : numbers[counter]) {
x += sum;
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
}
You don't need the inner loop. You can add each input to the sum after you store it in the array.
In addition, you should allocate the array once outside the outer loop, and not in each iteration.
double [] numbers = new double[entry];
for (counter = 0; counter< entry; counter++){
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
sum+= numbers[counter];
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
Put the sum and average logic outside the loop. This should work:
double [] numbers = new double[entry];
for (counter = 0; counter< entry; counter++){
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
sum += numbers[counter];
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
You can't use a for-each with a scanner. Also there is no need your you to be storing anything. Just keep track of the sum.
Scanner scanner = new Scanner(System.in);
System.out.println("How many entries would you like input?");
int numEntries = scanner.nextInt();
double sum = 0;
for (counter = 1; counter <= numEntries; counter++) {
System.out.println("Please input number " + counter + ": ");
sum += scanner.nextDouble();
}
System.out.println("The total sum is: " + sum);
System.out.println("The average is: " + sum / numEntries);
Same code, with average outside the loop and the useless array removed:
Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.println("How many entries would you like input");
int entry = scanner.nextInt();
for (int counter = 1; counter <= entry; counter++) {
System.out.println("Please input number " + counter);
sum += scanner.nextDouble();
}
System.out.println("The total sum is: " + sum);
double average = sum / entry;
System.out.println("The total average is: " + average);
Related
I was given the rainfall question where total rainfall is to be calculated for three months and then the average is to be determined however for some reason the loop will not end at three entries. I've defined the counter and have even used 'break' but for some reason the compiler just allows the user to keep entering. If the loop does not end I cannot calculate the average rainfall
I've defined the loop and created a while statement
import java.util.Scanner;
public class rainfall {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double average;
double total = 0;
final double rainfall[] = new double[3];
for (int counter = 0; counter <= rainfall.length; counter++) {
do {
System.out.print("Enter amount of rainfall:");
rainfall[counter] = input.nextInt();
} // end of do statement
while (rainfall[counter] <= 3);
} // end of for statement
for (int counter = 0; counter <= rainfall.length; counter++) {
System.out.println(counter + "t\t" + rainfall[counter]);
// display rainfall in the array
total = total + rainfall[counter]; //calculate total rainfall
System.out.println("Total rainfall is:" + total);
average = total / 3; //calculate average rainfall
System.out.print("Average rainfall is" + average);
}
}
}
I expect that the user could only enter results for three months and then the average will be given afterwards however the loop will not stop and hence the average can't be worked out.
That's the version which works:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double average;
double total = 0;
final double rainfall[] = new double[3];
for (int counter = 0; counter < rainfall.length; counter++) {
System.out.print("Enter amount of rainfall:");
rainfall[counter] = input.nextInt();
} // end of for statement
for (int counter = 0; counter < rainfall.length; counter++) {
System.out.println(counter + "t\t" + rainfall[counter]);
// display rainfall in the array
total = total + rainfall[counter]; //calculate total rainfall
System.out.println("Total rainfall is:" + total);
average = total / 3; //calculate average rainfall
System.out.print("Average rainfall is" + average);
}
}
The while loop was unnecessary and your for-loops with <= were actually designed for four elements instead of three.
You have a while loop that won't increment your for loop unless the input is greater than 3. You want to do something like this:
for (int counter = 0; counter < rianfall.length; counter++) {
System.out.print("Enter amount of rainfall:");
rainfall[counter] = input.nextInt();
total += rainfall[counter];
}
System.out.println("Total rainfall is:" + total);
average = total / rainfall.length; //calculate average rainfall
System.out.print("Average rainfall is" + average);
I condensed your two for loops into one and put the printing of the total and average outside the loop to only do it once.
I am new to programming and I started to practice with Java. In my exercice, im asked to write a program which calculates and prints out the sum of the digits of a number. Then it prints out all the divisors of the sum number.
The problem is that after that, i need to ask the user if they want to try another number and im not able to restart the program when the person answer "yes" . Thank you and sorry for my english !
//Introduction
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("yes")) {
System.out.println("Enter a number with a most 7-digits:");
while (input > 0);
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++)
if (sum % counter == 0)
System.out.print(counter + " ");
} if (choice.equals("no")) {
System.out.println("Thanks and Have a Great Day!");
You just have to make it so the loop restarts
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
while(input != -1){
int sum = 0;
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.print("Do you want another number? If you dont type -1: ");
input = mykeyboard.nextInt();
}
The code will keep going until the user types -1
The easiest way is to implement it is using your choice variable to control a loop condition:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
String choice = "yes";
while(choice.equals("yes")) {
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
choice = mykeyboard2.nextLine();
}
System.out.println("Thanks and Have a Great Day!");
while (input > 0);
This will go in an infinite loop. I think you put a ; instead of {.
Should be while (input > 0){
EDIT:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
while(true){
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("no")) {
break;
}
}
Here is the code but it's not optimized for all the exceptions. For example, if the user types 0 from the beginning, it will give the division by zero error and also I don't know why the sum of the numbers work.
Basically, I make num = 1 so it's different than 0 so the while loop can start, but in the end, I made sum = sum - 1; but it gave a wrong number.
Please help me.
import java.util.Scanner;
class Main {
public static void main (String[] args) {
int count = 0;
int num = 1;
double average = 0.0;
int soma = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Type a integer. 0 to exit.");
while (num != 0) {
num = scanner.nextInt();
sum = sum + num;
count++;
}
if (num == 0) {
average = sum / (count -1);
System.out.println("The sum of the numbers is: "+ soma);
System.out.println("The average of the numbers is: "+ media);
}
}
}
change while to do while:
do {
num = scanner.nextInt();
sum = sum + num;
count++;
}while (num != 0);
Change FROM:
average = sum / (count -1);
System.out.println("The sum of the numbers is: "+ soma);
System.out.println("The average of the numbers is: "+ media);
TO:
average = sum / (count);
System.out.println("The sum of the numbers is: "+ sum);
System.out.println("The average of the numbers is: "+ average);
it should work
Not sure where to begin honestly, I was able to find average using the user's input but can't seem to figure out the largest number or the smallest number from the numbers entered. Is there a method I can use? Any help would be great. Thank you.
EDIT: Somewhat figured it out. However the answers always seem to be largest number = 2.1478... or Smallest number = -2.1478...
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
double random = input.nextDouble();
double min = Integer.MIN_VALUE;
double max = Integer.MAX_VALUE;
double total=0;
int count = 1;
while (count < random+1) {
System.out.println("Enter grade " + count + ":");
double somenumber = input.nextDouble();
total+=somenumber;
count++;
if (somenumber > max){
max = somenumber;
}
if (somenumber < min){
min = somenumber;
}
}
System.out.println("Total is " + total);
System.out.println("Average is " + (total/random));
System.out.println("Largest number is " + max);
System.out.println("Smallest number is" + min);
}
}
You want some code that looks like
double min = Double.MAX_VALUE;
double max = 0.00; // assume use positive numbers
while (count < random+1) {
System.out.println("Enter grade " + count + ":");
double somenumber = input.nextDouble();
total+=somenumber;
count++;
max = Math.max (somenumber, max);
min = Math.min (somenumber, min);
}
EDIT Updated to use Double instead and now uses your original loop condition.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double smallest = Double.POSITIVE_INFINITY; //Initialize to largest int possible
double largest = Double.NEGATIVE_INFINITY; //Initialize to smallest int possible
System.out.println("Enter the number of grades: ");
double random = input.nextDouble();
int count = 1;
while (count < random + 1) {
System.out.print("Input Number: ");
Double x = input.nextDouble();
if (x < smallest) {
smallest = x;
}
if (x > largest) {
largest = x;
}
count++;
}
System.out.println("Smallest: " + smallest + ", Largest: " + largest);
}
}
Sample run:
run:
Enter the number of grades:
5
Input Number: 2.5454
Input Number: 3.454
Input Number: -100.54
Input Number: 5687
Input Number: 579873.5654
Smallest: -100.54, Largest: 579873.5654
BUILD SUCCESSFUL (total time: 15 seconds)
Thank you for the tips everyone. However, when I ran my program. I wasn't able to get the proper answers for the max and min value.
EDIT: SOLVED. THANK YOU ALL WHO CONTRIBUTED. <33
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
double random = input.nextDouble();
double min = Integer.MIN_VALUE;
double max = Integer.MAX_VALUE;
double total=0;
int count = 1;
while (count < random+1) {
System.out.println("Enter grade " + count + ":");
double somenumber = input.nextDouble();
total+=somenumber;
count++;
if (somenumber > max){
max = somenumber;
}
if (somenumber < min){
min = somenumber;
}
}
System.out.println("Total is " + total);
System.out.println("Average is " + (total/random));
System.out.println("Largest number is " + max);
System.out.println("Smallest number is" + min);
}
}
Largest number is 2.14748 Smallest number is -2.147478...That's what was printed...Am I making a arthimetic error?
Above while loop...
double max = 0;
double min = Double.MIN_VALUE;
In loop after you set some number...
if (someNumber > max){
max = someNumber;
}
if (someNumber < min){
min = someNumber;
}
Np glad it helped :) you should consider using a for loop instead of a while loop and declare someNumber outside of the loop like so:
double someNumber;
for (int i = 1; i <= random; i++){
//...
}
To make it even cleaner you could replace i <= random in the for loop with
i <= readNumGrades(input);
private double readNumGrades(Scanner in){
System.out.println("Enter the number of grades");
return in.nextDouble();
}
So you no longer need the variables count and random
public static void main(String[] args) {
int sum = 0;
int inputNum;
int counter;
float average;
double Max = 0;
double Min = 101;
Scanner NumScanner = new Scanner(System.in);
Scanner charScanner = new Scanner(System.in);
System.out.println("Enter the total number of exams you want a average");
counter = NumScanner.nextInt();
System.out.println("Please enter " + counter + " numbers:");
for(int i = 1; i<=counter ;i++){
inputNum = NumScanner.nextInt();
sum = sum + inputNum;
System.out.println();
if(inputNum > Max){
Max = inputNum;
}
if(inputNum < Min){
Min = inputNum;
}
if(inputNum > -1 && inputNum < 101){
sum = sum + inputNum;
}
else{
System.out.println("You entered a number that wasn't in the range of 0 to 100");
average = sum / counter;
}
}
}
}
Write a program using a loop that takes 10 values from a user representing exam grades (between 0 and 100) from the keyboard and outputs the minimum value, maximum value and average value of all the values entered. Your program should not accept values less than 0 or greater than 100. Problems with calculation of average and the program does not print out max and min values
How can I do this?
//This code is how to print out the max and min values of a list of numbers from the above program//
// Print out of max and min exam grades//
System.out.println( "Max Exam Score = " + Max );
System.out.println( "Minimum Exam Score = " + Min `enter code here`);