What I'm trying to make is an averaging program that takes any number of inputs. So far I need to have the user specify how many numbers they want to average, and if they don't give that many numbers the program crashes. Is there any way that I could just have them put as many numbers as they want and afterwards the array length is set?
Here is the code I am using right now:
import java.util.*;
public class Average_any
{
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println ("How many numbers do you want to enter?");
final int ARRAY_LENGTH = scan.nextInt();
System.out.println ("Please type the numbers you want to find the average of, "
+ "and then type \"Done\".");
System.out.println ("Warning: Only type the exact amount of numbers that you specified.");
// If user doesn't enter same number, results in crash
double[] numbers = new double [ARRAY_LENGTH];
do {
for (int i = 0; i < numbers.length; i++) {
while (!scan.hasNextInt()) {
System.out.println("That's not a number!");
scan.next(); //Need this to enter another input
}
numbers[i] = scan.nextInt();
}
} while (!scan.hasNext("Done"));
double total = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
double average = total/ARRAY_LENGTH;
System.out.println ("Your average is: " + average);
}
}
(Just in case anyone is wondering, no this is not a school assignment, I was just wondering because we did a simpler version in school)
Take the array out of the equation altogether
Scanner scan = new Scanner (System.in);
double total = 0;
int count = 0;
while (scan.hasNextDouble()) {
total += scan.nextDouble();
count ++;
}
double average = total / count;
Related
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 :)
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 know that scanf is not a java function, so i'm hoping someone can help me to understand how to convert this. Research on this topic is difficult to piece together.
This is my code:
import java.util.Scanner;
public class Average {
Scanner Scanner = new Scanner (System.in);
int main (){
int counter;
int number;
int total;
float average;
total = 0;
counter = 0;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
While (number != 0) {
total = total + number;
counter = counter + 1;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
}
if(counter != 0) {
average = (float) total / counter;
System.out.println("Average is %.2f\n", average);
} else {
System.out.println("No valid numbers have been entered.");
return 0;
}
}
}
use input like this`
public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use integer input
}
}
You cannot use the same name for the object as for the class. Change Scanner initialization as follows:
Scanner scanObj = new Scanner(System.in);
Replace all your scanf statements with the below:
number = scanObj.nextInt();
These are the changes done to your code:
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner Scanner = new Scanner (System.in);
int counter;
int number = 1;
int total;
float average;
total = 0;
counter = 0;
while(number != 0){
System.out.println("Enter the number 0 to end: ");
number = Scanner.nextInt();
System.out.printf("%d", number);
total = total + number;
counter = counter + 1;
}
if(counter != 0){
average = ((float)total /(float)counter);
System.out.printf("Average is %.2f\n", average);
}
else{
System.out.println("No valid numbers have been entered.");
//return 0;
}
}
}
First the Scanner takes the value the user entered. number = Scanner.nextInt(); This must be done inside your while loop since its the one that check the condition.
The next thing I changed was average = (float) total / counter;
This casts the total value only to a float. use brackets to both ends.
average = ((float)total /(float)counter); like this
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 + ".");
}
}