I would like to take my current program and separate the averging function in to a method out side of the main method. I would like to store the numbers grabbed with the scanner in to an array list and then use my averaging method to grab those number and average the numbers together. then Output the average in place of the current System.out.println your average is..
Please help me illustrate this. I am having trouble understanding how all this comes together.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
{
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
}
//added an import here
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
//main difference is the average calculation is done within a method instead of main
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) //input until user no longer wants to give input
{
if (count == 21)
{
break; //this command here jumps out of the input loop if there are 21
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble()); //simply adding to the array list
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr); //go to method calculate average, expect a double to be returned
System.out.println("Your average is: " + average);
}
private static Double calculate_average( ArrayList<Double> myArr ) //method definition
{
Double Sum = 0.0;
for (Double number: myArr) //for loop that iterates through an array list
{
Sum += number; //add all the numbers together into a sum
}
return Sum / myArr.size(); //return the sum divided by the number of numbers in the array list
}
}
This should help. Best of luck :)
Average avg = new Average();
... avg.add(scan2.nextDouble());
System.out.println("Your average is: " + Average.result());
public class Average {
void add(double x) { ... }
double result() { ... }
}
The thinking up the implementation I leave to you.
Here is some example code
private static void hoot(List<Double> kapow)
{
... do all the stuffs
}
public static void main(final String[] arguments)
{
List<Double> blam = new ArrayList<Double>();
blam.add(1.1);
blam.add(1.2);
blam.add(1.3);
hoot(blam);
}
Related
I am trying to write a program to read a series of numbers from the user until -1 is entered. It should then print the average (with decimals) of those numbers (not including the -1). This is what I have so far, but it does not seem to work properly whenever I input -1. This is what I have thus far:
import java.util.Scanner;
import java.util.*;
public class Tute1
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many numbers you want: ");
int numb = sc.nextInt();
int i =0;
int total =0;
while (i <= numb) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer ");
int myChoice=scan.nextInt();
total=total+myChoice;
i=i+1;
if(myChoice == -1) {
System.out.println("The average is "+ (total+1)/numb);
break;
}
}
System.out.println("The average is "+ total/numb);
}
}
Your code seems a bit odd. Here is how I would do it
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int total = 0;
while (true) {
System.out.println("Enter an integer ");
int myChoice = scan.nextInt();
if (myChoice != -1) {
total = total + myChoice;
i += 1;
} else {
break;
}
}
float average = total / i;
System.out.println("The average is " + average);
}
Hope this helps. You can add try-catch and stuff to make it so that user does not exploit this
Few things:
first of all you dont need to create a new scanner as your code inside the while loop. Its because the while loop is inside you function scope so every thing you declare on you function the while loop knows about. (It does not work the other way around)
second your breaking condition should be inside the while loop the if with break is redundant and unnecessary.
third thing you should get rid of numb as its doing nithung
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int numb = sc.nextInt();
int i =0;
int total =0;
while (numb != -1)
{
total=total+numb;
i=i+1;
int numb = sc.nextInt()
}
System.out.println("The average is "+ total/i);
}
}
I think this solution is smaller and more elegant
I simply cant figure out why I keep getting an indexoutofboundserror. I believe its pop up in the line
profits[i] = storeDays
The code is:
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 and its standard devation
//calcAverageProfit(dayProfitList);
}
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];
for(int i = 1; i<days +1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble(inputScan ner.nextLine());
profits[i] = storedDays;
}
return profits;
}
}
Arrays are enumarated from 0 so the first element of it is profits[0], next one is profits[1] and so on.
You are trying to reach an index that does not exist here:
for(int i = 1; i<days +1; i++) {
...
It actually should be
for(int i = 0; i<days; i++) {
...
I am trying to write a Java program that:
In the main method, prompt the user for an integer number.
Store the number in a variable called inputNum.
Pass the inputNum to a method called computeAvg.
In computeAvg, prompt the user to input double values as many times as inputNum. computeAvg method should calculate and return the average of real numbers that user entered.
Print the result in your main method.
This is my code
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
computeAvg();
}
public static void computeAvg() {
System.out.println(inputnum);
System.out.println("Enter double values as inputnum ");
int y;
y=keyboard.nextInt();
}
}
There are several changes to be done in your code:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
System.out.println("The average is"+computeAvg(inputnum));
}
public static double computeAvg(int y)
{
double[] arr = new double[y];
System.out.println(y);
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
double sum = 0;
for(double a:arr){
sum +=a;
}
System.out.println(sum);
double average = sum/arr.length;
return average;
}
First one is that the value you first taken as the user input must be passed to the method. Here I done it in computeAvg(inputnum) And expect this method to return a double value.
Second one is You should declare the method to return a value void means no return. change it to double
public static double computeAvg(int y)
take the parameter from the main method (value you taken from the user.)
If you need to store multiple values better solutions is array.(There are many methods bust for a beginner stick to arrays) crate a double array to take multiple double values.
double[] arr = new double[y];
next loop your code for the number of times the user input and take the double values.
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
next create a double value sum and get the addition and the divide it to get the average (another double value).
for(double a:arr){
sum +=a;
}
Finally return the average to the main method where it prints.
I used static Scanner keyboard = new Scanner(System.in); because I used the same scanner in both methods.
Feel free to ask any question regarding the code.
I hope the comments in the code are self explanatory for what the problem is asking and how the code works:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer? ");
// here you are asking for the number of double numbers that will be
// entered
int inputnum = keyboard.nextInt(); // asking for the int input (varibale
// is stored in inputnum)
System.out.println("Average for all " + inputnum + " numbers is: "
+ computeAvg(inputnum));
}
public static double computeAvg(int inputnum) {
Scanner keyboard = new Scanner(System.in);
double eachInput = 0.0;
double sumInputs = 0.0;
for (int counter = 1; counter <= inputnum; counter++) {
System.out.println("Please enter a double as input #" + counter
+ ": ");
eachInput = keyboard.nextDouble(); // asking for double input
sumInputs += eachInput; // adding up each input
}
// calculating and returning average
return sumInputs / (double) inputnum;
}
Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}
We have a java assignment where in we're supposed to develop a method that scans one line that is supposed to contain three double values and returns the largest. Throwing all possible exceptions is allowed.
Here is what I've done so far:
import java.util.Scanner;
public class s3dv {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double entered;
System.out.println("Enter 3 values to find the maximum:");
entered = input.nextDouble();
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
} // End getMaxValue method
}
I'm having an error at line 15.
change your code to
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
System.out.println("Enter 3 values to find the maximum:");
for(int i=0;i<3;i++){
entered[i] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
//Find maximum (largest) value in array using loop
public static double getMaxValue(double[] numbers){
double maxValue = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i]; } } return maxValue;
}
You cannot give a double parameter to a method while it expects a double array. And also you request user to enter double value only once, you should repeat that procedure. Change your main method to this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double[] entered = new double[3];
int counter = 0;
while (counter != 3)
{
System.out.println("Enter a double value:");
entered[counter++] = input.nextDouble();
}
System.out.println("Maximum is - " + getMaxValue(entered));
}
Your getMaxValue() method seems OK, however when entering doubles from console use comma(,) instead of dot(.), you might get InputMismatchException otherwise.
this main code will read the 3 double value in a single line, split them and pass it to the getMaxValue
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userLine, lineSplitted[];
System.out.println("Enter 3 values to find the maximum:");
userLine = input.nextLine();
lineSplitted=userLine.split(" ");
double entered[]=new double[lineSplitted.length];
for (int i=0; i<lineSplitted.length; i++) entered[i]=Double.valueOf(lineSplitted[i]);
System.out.println("Maximum is - " + getMaxValue(entered));
}