How do I computer average into a method? - java

I'm attempting to call a method in order to calculate average (calcavgnow).. I'm trying to have it calculate the average of all the numbers in the array and return the average to the caller. I'm hoping it can deal with any size array. I tried attempting below.. can anyone help me figure out what I am doing wrong?
import javax.swing.JOptionPane;
public class sdasfs {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
calcavgnow = total / SelectNumber;
}
JOptionPane.showMessageDialog(null, getTotal(numbers) + " divided by " + Numbers.length + " is " + getAvg(Numbers));
}
//Create method in order to calculate calcavgnow
public static double getAvg(int numbers[]){
return (double)getTotal(numbers)/numbers.length;
}
public static int getTotal(int numbers[]){
int total = 0;
for(int i:numbers)
total +=i;
return total;
}
}// end class

Have a separate method to calculate average. Don't do everything inside the same method. Learn to modularize your code. So others can easily get adopt to your code.
public static double getAvg(double numbers[]){
return getTotal(numbers)/numbers.length;
}
public static double getTotal(double numbers[]){
double total = 0;
for(double i:numbers)
total +=i;
return total;
}

import javax.swing.JOptionPane;
public class AvgCalculator {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
}
calcavgnow = total / SelectNumber;
JOptionPane.showMessageDialog(null, "The average entered is " + calcavgnow);
}
}

Related

Java Average of integers

i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.
Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);

What am I missing from my code to meet all the requirements of my program?

I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.
public class Table {
public static void main(String [] strAng) {
int sum = 0;
double average;
int min = 1;
int max = 10;
for(int number = min;
number <= max; ++number) {
sum += number;
}
System.out.print("Sum:" +sum);
System.out.print("Average:" +average);
You have not get an input from user and also you do nothing to make average.
Try this code, and if you have other requirements, update the question.
int sum = 0;
double average;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the integers with space between each two integer: ");
String inputNumberFilePath = userInputScanner.nextLine();
String[] numStrArray = inputNumberFilePath.split(" ");
for (String string : numStrArray) {
sum += Integer.parseInt(string);
}
average = (double) sum / (double) numStrArray.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
output sample:
Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.
import java.util.*;
public class Table {
This part is used to read ANY user input Strings included.
public static String getInput(){
String outPut = "";
System.out.println("Type something to parse: ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextLine()) {
outPut = sc.nextLine();
}
return outPut;
}
Here we build our "bar graph":
public static Map<Long,Integer> makeTable(String input){
Map<Long,Integer> table = new HashMap<>();
long in = Long.parseLong(input);
long lastDig = 0;
int count = 1;
while(in > 0){
lastDig = in % 10;
in /= 10;
if(!table.containsKey(lastDig)) {
table.put(lastDig, count);
} else {
table.replace(lastDig,count,count+1);
}
}
return table;
}
Here we calculate the sum:
public static int sum(Map<Long,Integer> table){
int sum = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
}
return sum;
}
Here we get our average:
public static int average(Map<Long,Integer> table){
int sum = 0;
int divisor = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
divisor += table.get(key);
}
return sum/divisor;
}
public static void main(String[] args){
int sum = 0;
double average = 0;
String input = "";
input = getInput();
System.out.println("Unsanitized In: " + input);
Here the integer digits are extracted!
input = input.replaceAll("[^\\d.]","");
Long.parseLong(input);
System.out.println("Sanitized In: " + input);
Map<Long,Integer> myMap = makeTable(input);
System.out.println(myMap);
System.out.println("Sum:" +sum(myMap));
System.out.print("Average:" + average(myMap));
}
}
Our example output for: asdf45313ha is:
Unsanitized In: asdf45313ha
Sanitized In: 45313
{1=1, 3=2, 4=1, 5=1}
Sum:16
Average:3

Changing input variables in a java loop

I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?
You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}
So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}

Cannot find symbol in return statement and average issue

I'm having two issues in this code where I'm getting and a lossy conversion error
for double to int. No idea how to approach that. (code directly below following lines)
and My average or mean finder keeps giving me incorrect answers when I input numbers with decimals. Any help would be greatly appreciated.
public static double findMaxNumber(double maxNumber, double [] profit) {
double theLowestValue = profit[maxNumber];
import java.util.Arrays;
import java.util.Scanner;
class Business
{
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("Welcome to the profit-calculation program.");
System.out.println("how many days of data do you have?");
int n = Integer.parseInt (inputScanner.nextLine());
//call upon a function to store the profits into an array for further use.
double[] dayProfitList = inputProfit(n);
//call upon a function to calculate average profit
double averageValue = calcAverageProfit(dayProfitList);
System.out.println("the average of these values is " +calcAverageProfit(dayProfitList) + "."); //print out devised average
//call upon a function to calculate standard devation
double standardDeviation = calcStandardDeviation(averageValue, dayProfitList);
System.out.println("the standard deviation is plus or minus " +calcStandardDeviation(averageValue, dayProfitList));
//find the most profitable day
double theMax = findMax(dayProfitList);
System.out.println("the most profitable day was " + findMax(dayProfitList));
findMaxNumber(theMax, dayProfitList);
System.out.println("and the value earned that day was " + findMaxNumber(theMax, dayProfitList));
findLeast(dayProfitList);
System.out.println("the least profitiable day was " + findLeast(dayProfitList));
}
//function to store each days profits within an array
public static double[] inputProfit(int days) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("input the profit on..");
double[] profits = new double [days+1];
for(int i = 1; i<days + 1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble (inputScanner.nextLine());
profits[i] = storedDays;
}
return profits;
}
//fuction to calculate the profit of said days.
public static double calcAverageProfit(double [] profit){
double sum = 0;
double average = 0;
for(int i = 1; i<profit.length; i++){
sum = profit[i] + sum;
}
average = sum/profit.length;
return average;
}
public static double calcStandardDeviation(double average, double[] profit){
double stepThree = 0;
double sum = 0;
double product = 0;
for(int i = 1;i<profit.length; i++) {
sum = profit[i] - average;
product = sum * sum;
stepThree = product + stepThree;
}
double standardDeviation = stepThree/profit.length;
java.lang.Math.sqrt(standardDeviation);
return standardDeviation;
}
public static double findLeast(double [] profit){
double least = profit[0];
for (int i = 1; i<profit.length; i++) {
if (profit[i]>least)
least = profit[i]; }
return least;
}
public static double findMaxNumber(double maxNumber, double [] profit) {
int MaxNumberInt = (int) maxNumber;
double theLowestValue = profit[maxNumber];
return theLowestValue; }
For fix double to int conversion error, you have to change your code as below.
from
double theLowestValue = profit[maxNumber];
to
double theLowestValue = profit[MaxNumberInt];
After changed, it should below as below.
public static double findMaxNumber(double maxNumber, double[] profit) {
int MaxNumberInt = (int) maxNumber;
double theLowestValue = profit[MaxNumberInt];
return theLowestValue;
}
In your average/mean finder iterate profit[] array from 0th index.
public static double calcAverageProfit(double [] profit) {
...
for (int i = 0; i < profit.length; i++) {
...
}
}

Ending a program with ctrl+Z

import java.util.Scanner;
public class ClassAverage
{
public static void main(String args[])
{
String names[] = new String[50];
int scores[] = new int[50];
int entries = 0;
Scanner in = new Scanner(System.in);
//System.out.println("Enter number of entries");
//int entry = in.nextInt();
System.out.println("Enter the names followed by scores of students: ");
for(int i = 0; i < 50; i++)
{
names[i] = in.next();
scores[i] = in.nextInt();
entries++;
}
Average avg = new Average();
double average = avg.CalcAvg(scores,entries);
System.out.println("The class average is: " + average);
avg.belowAvg(scores,average,names,entries);
avg.highestScore(scores,names, entries);
}
}
class Average
{
Average()
{
System.out.println("The averages: ");
}
double CalcAvg(int scores[], int entries)
{
double avg;
int total = 0;
for(int i = 0; i < entries; i++)
{
total += scores[i];
}
avg = total/entries;
return avg;
}
void belowAvg(int scores[],double average,String names[], int entries)
{
for(int i = 0; i < entries; i++)
{
if(scores[i] < average)
System.out.println(names[i] + "You're below class average");
}
}
void highestScore(int scores[],String names[], int entries)
{
int max = scores[1];
for(int i = 0; i < entries; i++)
{
if(scores[i]>=max)
max=scores[i];
}
System.out.println("The maximum score is: " + max);
System.out.println("The highest score acheivers list: ");
for(int i = 0; i < entries; i++)
{
if(scores[i] == max)
System.out.println(names[i]);
}
}
}
im suppose to hold the ctrlkey press z and then press the enter key to end the program but how do i do that?
if you are wondering the program is to write a program that lets the user input student names followed by their test scores and outputs the class average, names of students below the average, and the highest test score with the name of student
Ctrl-Z is the DOS command code for end of input (the UNIX equivalent is Ctrl-D). All command line programs should support this because it allows you to pipe output from one as input to the other. Kudos to your teacher!
When this key combo is pressed, Scanner.hasNextLine() will return false. Here's an example of a loop that reads line until you hit Ctrl-Z on Windows (or Ctrl-D on Linux/Unix):
while (in.hasNextLine()) {
System.out.println("You wrote " + in.nextLine());
}
You can listen for the control-z character in your scanner:
String nextLine = in.nextLine();
if(nextLine.length == 1 && nextLine.charAt(0) == KeyEvent.VK_Z)
// end program

Categories