I made a java command line program for calculating sum and average of an arbitary series of numbers, but I am wondering is there any better way for making it shorter and maybe without an array?
public class Main {
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Program for calculating sum and average of an arbitary series of numbers");
System.out.println("------------------");
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to calculate? ");
int nums = input.nextInt();
int array[] = new int[nums];
int sum = 0;
for (int i=0; i<nums; i++){
System.out.print("Enter " + (i+1) + ". number: ");
array[i] = input.nextInt();
}
for (int i=0; i<array.length; i++){
sum= sum + array[i];
}
System.out.println("Sum is: " + sum);
System.out.print("Average is: " + (sum/nums));
}
}
You have two for loops in your code. The first one writes values to an array, and the second one reads them to get their sum. You don't really need both of those loops (or the array). You can sum the values as you read them in, then calculate the average based on the sum.
Note, though, that if you want to extend your code later to calculate other stats on the entered data (e.g., standard deviation) it will be easier to work with the data stored in an array.
You don't need to store these numbers to an array.
Usage of BufferedReader is inexpensive over Scanner in this case. Refer reasons to consider using BufferedReader.
public static void main(String[] args) throws IOException {
System.out.println("------\nProgram for calculating sum and average of integers\n------");
System.out.print("Enter space separated integer values: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] split = reader.readLine().split("\\s");//splits string on whitespaces
double sum=0, average;
for (String numberString : split)
sum += Integer.parseInt(numberString);
average = sum / split.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
A simple solution, where the user does not have to enter the number of the numbers first.
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Program for calculating sum and average of an arbitary series of numbers");
System.out.println("------------------");
Scanner input = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.print("Input numbers. Input something else (e.g. enter) if you're finisehd:\n");
while (true) {
try {
values.add(Integer.parseInt(input.nextLine()));
} catch (Exception e) {
break;
}
}
System.out.println("Sum is : " + values.stream().mapToInt(Integer::intValue).sum());
System.out.println("Average is: " + values.stream().mapToInt(Integer::intValue).average().getAsDouble());
}
Related
I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.
I am learning Java and am having a very simple problem.
How to print the final sum from a while loop?
if I enter integers 10 10 40
the output I get is
10
20
60
but am only trying to get the final 60.
This answer can also relate to printing the final anything in a while loop as I just can't seem to get this.
my sample code below...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
System.out.println("The Sum is: " + total);
}
}
Your main problem is that you have put the print statement inside the loop.
Also, in.hasNextDouble() doesn't make sense for input from the keyboard; it is useful when you are reading data from a file or a Scanner for some string. You can use an infinite loop (e.g. while(true){...}) and break it when there is no input from the user.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up, press Enter without any input to exit: ");
double total = 0;
while (true) {
String input = in.nextLine();
if (input.isBlank()) {
break;
}
total += Double.parseDouble(input);
}
System.out.println("The Sum is: " + total);
}
}
A sample run:
Enter a sequence of numbers to sum up, press Enter without any input to exit:
10
20
30
The Sum is: 60.0
A demo of a Scanner for a string:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner("10 20 30");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
}
Output:
The Sum is: 60.0
The problem lies in: System.out.println("The Sum is: " + total);
If you would like for only the final sum to be printed it needs to be outside of the while loop.
Please, print the total outside of the loop and it will work fine !
Code:
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
I've created this class in a separate file and the program runs. The questions I have is the for a loop. Currently, I'm using a final int. I wanted to input a variable for
ol < MAX_R
} // End input loop
// Added feature that is not part of grading
System.out.print("Press enter to see results: ");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
Well, I think that author wants to read round scores for input stream and calculate an average. This is pretty simple, I think. First, you have to split your method into required logical parts: read data from stream, data processing, output data (to make your code simple and clear).
Java is not a C++. Here you can define array size wherever you like, as well as using user's input at runtime (Java does not require to know size of array at compile time).
public class Foo {
public static void main(String... args) {
double[] scores = readRoundScores();
double avg = calcAverageScore(scores);
System.out.println("\nAverage score: " + avg);
}
private static double[] readRoundScores() {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter total rounds: ");
double[] scores = new double[scan.nextInt()];
for (int i = 0; i < scores.length; i++) {
System.out.printf("Enter your round %d score: ", i + 1);
scores[i] = scan.nextDouble();
}
return scores;
}
}
private static double calcAverageScore(double... scores) {
double sum = 0;
for (double score : scores)
sum += score;
return sum / scores.length;
}
}
Im extremely new at Java programming and my professor asked us to write a program that can:
Show each grade by the letter. (Ex: A, B, C, D, F)
Show the Minimum & Average grade of the class
Show the number of people who passed the exam (70+ is passing)
I have been trying to use arrays and if else statements to solve this but Im not making much progress. Can you guys please help me out?
I know I'm not good at coding, but here is something I am trying.
I also would like to incorporate if else statements in my code to make things simpler.
Thank you so much in advance.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] grades = new double[10];
int sum
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
System.out.print ("Enter number " + (index+1) + ": ");
grades[index] = scan.nextDouble();
}
}
}
Finding the minimum value is done by using a for loop just like your current one and using:
min = Math.min(min, grades[index]);
The average can be found just by finding the sum inside the loop:
sum += grades[index];
And then divide by the number of values.
The number of grades 70+ can be found with an if statement inside the loop:
if (grades[index] >= 70) {
numPassing++;
}
Each of these operations can also be done using DoubleStream from Java 8:
double min = Arrays.stream(grades).min().orElse(0.0);
double avg = Arrays.stream(grades).average().orElse(0.0);
long numPassing = Arrays.stream(grades).filter(grade -> grade >= 70).count();
Okay I modified the code a bit, plus I didn't used any functionalities provided in java so that you can understand the flow control and logic as being a newbie to java.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] marks = new double[10];
char[] grades=new char[10];
int[] numGradeStudent={0,0,0,0,0};
int min=0,avg=0,minIndex=0;
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
//Taking marks then applying grades and counting no. of students
System.out.print ("Enter number " + (index+1) + ": ");
marks[index] = scan.nextDouble();
if(marks[index]>90)
grades[index]='A';
if(marks[index]>75 && marks[index]<=90)
grades[index]='B';
if(marks[index]>65 && marks[index]<=75)
grades[index]='C';
if(marks[index]>55 && marks[index]<=64)
grades[index]='D';
else
grades[index]='E';
//Setting up graded students down from here
if(grades[index]=='A')
numGradeStudent[0]++;
if(grades[index]=='B')
numGradeStudent[1]++;
if(grades[index]=='C')
numGradeStudent[2]++;
if(grades[index]=='D')
numGradeStudent[3]++;
if(grades[index]=='E')
numGradeStudent[4]++;
}
min=numGradeStudent[0];
for(int i=0;i<5;i++){
if(numGradeStudent[i]<min){
min=numGradeStudent[i];
minIndex=i;
}
}
System.out.println("Min grade of class is:"+ grades[minIndex]);
for(int i=0;i<10;i++){
if(marks[i]>70)
System.out.println("Student "+(i+1)+" passed.");
}
}
}
i apologize i know this looks simple but i'm kinda new to coding. the goal of the program is to take inputs from the user starting at index 0 and then save the inputs into the array. i'm probably close to solving this but i need some help.
here is the code:
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[numberOfGrades] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
Your logic is a bit off. numberOfGrades is the.. well.. number of grades. And when you do this: grades[numberOfGrades] = input.nextInt(); then you put the user's input in the grades array in location numberOfGrades, which you don't want.
What you do want is:
do {
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
This way, the array in location counter is accessed, and the user's input is placed inside it in the correct location.
Also, to calculate the average of the grades, like you are trying to do in the end of your program, you should do:
double sum = 0;
for (int grade : grades)
sum += grade;
And then your average will be:
average = 1.0d * sum / grades.length;
You can just as well put this summing logic inside your do-while loop and avoid the extra loop I introduced.
this instruction
grades[numberOfGrades] = input.nextInt();
must be replaced by
grades[counter] = input.nextInt();
try this ...
The thing that you were doing wrong is in the do while loop you were inserting value in the same array index grades[numberOfGrades] = input.nextInt(); should be replaced by grades[counter] = input.nextInt();
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
You can try like this
public class ArrayTest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter number of elements");
int n=input.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=input.nextInt();
}
for(int i: arr){ //for printing array
System.out.println(i);
}
}