(Java) Statistics program - java

I am trying to write a program that does the following.
1) Prompts user for a integer and stores it.
2) Uses the users input to calculate the
*Arithmetic Mean
*Geometric Mean
*Min and Max of the number that they just entered.
I've done most of it and from what I see, I asked the User for a input and stored it under the variable userInput in
the first method.
I am not sure on how to use the userInput for Arithmetic Mean, Geometric Mean, and Min and Max.
public class SimpleStatistics {
public static double[] getUserInput() {
// Returns a string of doubles
Scanner sc = new Scanner(System.in);
// Create list
List<Double> inputList = new ArrayList<Double>();
// Getting input
System.out.println("Please enter number");
double userInput = sc.nextDouble();
// See our new list
System.out.println(inputList);
double arr[] = new double[inputList.size()];
System.out.println(inputList.size());
return arr;
}
public static double arithmeticMean(double[] nums) {
double mean = 0;
double sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
mean = sum / nums.length;
return mean;
}
public static double geometricMean(double[] nums) {
double gm = 1.0;
for (int i = 0; i < nums.length; i++) {
gm *= nums[i];
}
gm = Math.pow(gm, 1.0 / (double) nums.length);
return gm;
}
public static double[] minAndmax(double[] nums) {
double min = nums[0];
double max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
} else if (nums[i] > max) {
max = nums[i];
} else {
}
}
double[] minAndmax = { min, max };
return minAndmax;
}
public static double[] scaleUp(double[] nums, int factor) {
for (int i = 0; i < nums.length; i++) {
nums[i] *= factor;
}
return nums;
}
public static double[] scaleDown(double[] nums, int factor) {
for (int i = 0; i < nums.length; i++) {
nums[i] /= factor;
}
return nums;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] input = { 1, 2.8, 5.3, 100, -5, -6.5 };
System.out.println("Choose a option 1-6");
boolean exit = false;
while (!exit) {
System.out.println();
System.out
.println("1) Arithmetic mean, 2) Geometric mean, 3) minAndmax, 4) Scale Up, 5) Scale Down, 6) Quit");
System.out.print("Input -> ");
int choice = sc.nextInt();
System.out.println();
switch (choice) {
case 1: {
// Arithmetic mean
System.out.println("Arithmetic mean");
System.out.println(arithmeticMean(input));
break;
}
case 2: {
// Geometric mean
System.out.println("Geometric mean");
System.out.println(arithmeticMean(input));
break;
}
case 3: {
// Min and max
System.out.println("Min and Max");
for (double i : minAndmax(input)) {
System.out.print(i + ", ");
}
break;
}
case 4: {
// Scale Up
System.out.println("Scale Up");
System.out
.print("Please enter factor by which you want to scale -> ");
int factor = sc.nextInt();
for (double i : scaleUp(input, factor)) {
System.out.print(i + ", ");
}
break;
}
case 5: {
// Scale Down
System.out.println("Scale Down");
System.out
.print("Please enter factor by which you want to scale -> ");
int factor = sc.nextInt();
for (double i : scaleDown(input, factor)) {
System.out.print(i + ", ");
}
break;
}
case 6: {
exit = true;
break;
}
}
}
}
}

You are not actually adding your number to your double array. Change your getUserInput() function to the following:
public static double[] getUserInput() {
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers are you entering?");
double[] arr = new double[sc.nextInt()];
for (int i = 0; i < arr.length; i++) {
System.out.println("Please enter your number");
arr[i] = sc.nextDouble();
}
sc.close();
return arr;
}

Change the getUserInput method to this:
public static double[] getUserInput() {
Scanner sc = new Scanner(System.in);
List<Double> inputList = new ArrayList<Double>();
System.out.println("Please enter how many numbers you will be inputing");
int numberOfInputs = sc.nextInt();
for (int i = 0; i < numberOfInputs; i++) {
System.out.println("Please enter a number");
double userInput = sc.nextDouble();
inputList.add(userInput);
}
sc.close();
double[] arr = new double[inputList.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = inputList.get(i);
}
return arr;
}
Then, in your main method, use the input by calling the method. E.g.
// Arithmetic mean
System.out.println("Arithmetic mean");
System.out.println(arithmeticMean(getUserInput()));
break;
I'm always happy to help, please ask if there is anything else.

Related

How would I stop a negative value from input being stored in an array?

The code takes an x and y coordinate, however I don't want any negative values to be stored in the array. How would I go about in doing this as I can only break away from the loop but can't seem to avoid storing the negative value.
import java.util.Scanner;
class ConvexHull {
static int loadPoints(int maxPoints, double[] xVal, double[] yVal) {
int numPoints = 0;
Scanner scan = new Scanner(System.in);
for(int i = 0; i < xVal.length; i++) {
System.out.println("Insert a x value: ");
xVal[i] = scan.nextDouble();
if(xVal[i] < 0) {
break;
}
if(xVal[i] > maxPoints) {
System.out.println("Maximum capacity for array has been reached");
break;
}
System.out.println("Insert a y value: ");
yVal[i] = scan.nextDouble();
if(yVal[i] < 0) {
break;
}
if(yVal[i] > maxPoints) {
System.out.println("Maximum capacity for array has been reached");
break;
}
}
numPoints = yVal.length;
scan.close();
return numPoints;
}
public static void main(String[] args) {
int maxPoints = 70;
double[] xVal = new double[maxPoints];
double[] yVal = new double[maxPoints];
loadPoints(maxPoints, xVal, yVal);
for(int x= 0; x < xVal.length; x++) {
System.out.println(xVal[x] + "," + yVal[x]);
}
}
}
The problem is that doing xVal[i] = scan.nextDouble(); puts the value into the array before the check. Doing something like
// Read in the next double
double nextX = scan.nextDouble();
// If the next double is negative, break out of the loop
if (nextX < 0) {
break;
}
xVal[i] = nextX;
...
// Same format for yVal
Test the value first. But if you have different arrays of the same type, make a method.
public static int insert(double[] arr, double val, int i) {
if(i >= arr.length) {
System.out.println("Array has reached capacity");
return -2;
}
if (val < 0) {
return -1;
}
arr[i] = val;
return 0; // ok.
}

Can you help me with my codes about methoding?

I need some help with my homework, so basically we need to create a code in which we input 10 numbers in an array, then search the array if my inputted number is there, most of the code is done. I just need to method the loop for searching if the inputted number is in the array Thanks for the help!!!
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
for(i = 0; i < 10; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
i = find(a, 10, x);
if(i != -1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
private static int find(int a[],int n, int x) {
int i, flag = 0;
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1) {
return i;
} else {
return -1;
}
}
public class Main {
public static int findIndexOfNumber(int numberToSearch, int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if(numbers[i]==numberToSearch) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++) {
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
flag = findIndexOfNumber(x, a);
System.out.println("The value "+x+" is found at index "+flag);
}
}
You can try this also

How to initialize variable back to 0 in a while loop in java?

I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}

Java Error after program runs

My program does everything I want it to do, but AFTER it's done running I get this error that pops up. Looking through my code I cannot find where the error occurs.
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1465)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at simplestatistics.SimpleStatistics.main(SimpleStatistics.java:102)
Input -> Java Result: 1
package simplestatistics;
import java.util.*;
import java.lang.*;
import java.util.InputMismatchException;
public class SimpleStatistics {
public static double[] getUserInput(Scanner sc) {
List<Double> inputList = new ArrayList<Double>();
System.out.println("Please enter how many numbers you will be inputing");
int numberOfInputs = sc.nextInt();
for (int i = 0; i < numberOfInputs; i++) {
System.out.println("Please enter a number");
double userInput = sc.nextDouble();
inputList.add(userInput);
}
sc.close();
double[] arr = new double[inputList.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = inputList.get(i);
}
return arr;
}
public static double arithmeticMean(double[] nums) {
double mean = 0;
double sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
mean = sum / nums.length;
return mean;
}
public static double geometricMean(double[] nums) {
double gm = 1.0;
for (int i = 0; i < nums.length; i++) {
gm *= nums[i];
}
gm = Math.pow(gm, 1.0 / (double) nums.length);
return gm;
}
public static double[] minAndmax(double[] nums) {
double min = nums[0];
double max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
} else if (nums[i] > max) {
max = nums[i];
} else {
}
}
double[] minAndmax = {min, max};
return minAndmax;
}
public static double[] scaleUp(double[] nums, int factor) {
for (int i = 0; i < nums.length; i++) {
nums[i] *= factor;
}
return nums;
}
public static double[] scaleDown(double[] nums, int factor) {
for (int i = 0; i < nums.length; i++) {
nums[i] /= factor;
}
return nums;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] input = {1, 2.8, 5.3, 100, -5, -6.5};
System.out.println("Choose a option 1-6");
boolean exit = false;
while (!exit) {
System.out.println();
System.out.println("1) Arithmetic mean, 2) Geometric mean, 3) minAndmax, 4) Scale Up, 5) Scale Down, 6) Quit");
System.out.print("Input -> ");
int choice = sc.nextInt();
System.out.println();
switch (choice) {
case 1: {
// Arithmetic mean
System.out.println("Arithmetic mean");
System.out.println(arithmeticMean(getUserInput(sc)));
break;
}
case 2: {
// Geometric mean
System.out.println("Geometric mean");
System.out.println(arithmeticMean(getUserInput(sc)));
break;
}
case 3: {
// Min and max
System.out.println("Min and Max");
for (double i : minAndmax(getUserInput(sc))) {
System.out.print(i + ", ");
}
break;
}
case 4: {
// Scale Up
System.out.println("Scale Up");
System.out.print("Please enter factor by which you want to scale -> ");
int factor = sc.nextInt();
for (double i : scaleUp(input, factor)) {
System.out.print(i + ", ");
}
break;
}
case 5: {
// Scale Down
System.out.println("Scale Down");
System.out.print("Please enter factor by which you want to scale -> ");
int factor = sc.nextInt();
for (double i : scaleDown(input, factor)) {
System.out.print(i + ", ");
}
break;
}
case 6: {
exit = true;
break;
}
}
}
}
}
Here's the link to my code
https://gist.github.com/Chunky1022/0775fba6692456ae1c8c#file-gistfile1-txt
At the first call of getUserInput you close the scanner.
public static double[] getUserInput(Scanner sc) {
...
sc.close();
...
}
Simply remove the sc.close line.
If you really want to close it, then close it when you are sure you won't use this scanner anymore. However, I don't see why you would close System.in.

Java program asking for 10 numbers and puts them in an array. How do I ask for input? Is my code correct so far?

This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}

Categories

Resources