how can i save input from joptionpane as an array? - java

import javax.swing.JOptionPane;
public class ArrayOperations
{
public static void main(String[] args)
{
String[] numbers;
numbers = JOptionPane.showInputDialog("Enter your numbers: ");
int numbers1 = Integer.parseInt(numbers);
JOptionPane.ShowMessageDialog(null, "The sum of your numbers is: "
+ getTotal() + "\nThe average of your numbers is: " + getAverage()
+ "\nThe highest number was: " + getHighest + "The lowest number "
+ "was: " + getLowest());
}
public static double getTotal()
{
//Accumulate sum of elements in numbers1 array and return total
double total = 0.0;
for (int index = 0; index < numbers1.length; index++)
total += numbers1[index];
return total;
}
public static double getAverage()
{
//Get average
return getTotal() / numbers1.length;
}
public static double getHighest()
{
//Find highest number entered
double highest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] > highest)
highest = numbers1[index];
}
return highest;
}
public static double getLowest()
{
//Find lowest number entered
double lowest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] < lowest)
lowest = numbers1[index];
}
return lowest;
}
}
So...basically i'm in chapter seven of this starting out with java book and a lot of people's answers are prone to using methods we haven't covered yet... (we are just now learning about arrays) and quite frankly I have no idea how to save user input in an array... I would really appreciate some help. There are actually a plethora of errors with this code, but I figure if I figure out the main one, maybe it'll help me solve the rest of them.
ArrayOperations.java:19: error: incompatible types: String cannot be converted to String[]
numbers = JOptionPane.showInputDialog("Enter your numbers: ");

I changed many thing in your code.
01) Taking a string as input and create a array using the no of white spaces then the string is broken to int array.
02) Passing an array to each and every method so all the elements are calculated.
The code:
import javax.swing.JOptionPane;
public class ArrayOperations
{
public static void main(String[] args)
{
String numbers;
numbers = JOptionPane.showInputDialog("Enter your numbers: ");
int count = 0;
for(int i = 0; i < numbers.length(); i++) {
if(Character.isWhitespace(numbers.charAt(i))) count++;
}
int [] numbers1 = new int [++count];
for(int n = 0; n < count; n++) {
numbers1[n] = Integer.parseInt(numbers.split(" ")[n]);
}
JOptionPane.showMessageDialog(null, "The sum of your numbers is: "
+ getTotal(numbers1) + "\nThe average of your numbers is: " + getAverage(numbers1)
+ "\nThe highest number was: " + getHighest(numbers1) + "\nThe lowest number "
+ "was: " + getLowest(numbers1));
}
public static double getTotal(int[] numbers1)
{
//Accumulate sum of elements in numbers1 array and return total
double total = 0.0;
for (int index = 0; index < numbers1.length; index++)
total += numbers1[index];
return total;
}
public static double getAverage(int[] numbers1)
{
//Get average
return (getTotal(numbers1) / numbers1.length);
}
public static double getHighest(int[] numbers1)
{
//Find highest number entered
double highest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] > highest)
highest = numbers1[index];
}
return highest;
}
public static double getLowest(int[] numbers1)
{
//Find lowest number entered
double lowest = numbers1[0];
for (int index = 1; index < numbers1.length; index++)
{
if (numbers1[index] < lowest)
lowest = numbers1[index];
}
return lowest;
}
}
Hope that this is what you needed.

Related

How can I print the max and min value of an array?

I need to write a program that stores the total rainfall for 12 months then show an output of the total, average, the month with the highest, and lowest rainfall. My program runs but but I don't know how to make the output the number of the month instead of the amount of rainfall in that month.
For example when I have, Enter rain fall for month 6: 15.6 My output should be 6 not 15.6. Thanks for your help.
import java.util.Scanner;
public class Rainfall
{
public static void main (String [] args)
{
double[] rain = new double[12]; // The rainfall data
getValues(rain);
showValues(rain);
System.out.println("The total rainfall for this year is: " + totalRain(rain));
System.out.println("The average rainfall for this year is: " + averageRain(rain));
System.out.println("The month with the highest amount of rain is: " + mostRain(rain));
System.out.println("The month with the lowest amount of rain is: " + leastRain(rain));
}
/**
showValues method
#param rain Display the rainfall array
*/
public static void showValues(double[] rain)
{
}
/**
getValues method
#return The rain array filled with user input
*/
public static void getValues(double[] array)
{
Scanner scan = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.println("Enter rain fall for month " + (i + 1) + ".");
array[i] = scan.nextDouble();
}
}
/**
getTotal method
#return The total of the elements in
the rainfall array.
*/
public static double totalRain(double[] rain)
{
double total = 0.0; // Accumulator
// Accumulate the sum of the elements
// in the rainfall array.
for (int index = 0; index < rain.length; index++)
//total += sales[index];
total = total + rain[index];
// Return the total.
return total;
}
/**
getAverage method
#return The average of the elements
in the rainfall array.
*/
public static double averageRain(double[] rain)
{
return totalRain(rain) / rain.length;
}
/**
getHighest method
#return The highest value stored
in the rainfall array.
*/
public static double mostRain(double[] rain)
{
double highest = rain[0];
for (int index = 1; index < rain.length; index++)
{
if (rain[index] > highest)
highest = rain[index];
}
return highest;
}
/**
getLowest method
#returns The lowest value stored
in the rainfall array.
*/
public static double leastRain(double[] rain)
{
double lowest = rain[0];
for (int index = 1; index < rain.length; index++)
{
if (rain[index] < lowest)
lowest = rain[index];
}
return lowest;
}
}
Here is a pretty simple method using JAVA 8 Streams:
Double[] doubles = new Double[12];
List<Double> doubleList = Arrays.asList(doubles);
Double max = doubleList.stream().mapToDouble(dub -> dub).max().getAsDouble();
Double min = doubleList.stream().mapToDouble(dub -> dub).min().getAsDouble();
Try this: Instead of the amount of rain at the given index, you'd want the index istelf.
public static double mostRain(double[] rain)
{
double highest = rain[0];
int highestMonth = 0;
for (int index = 1; index < rain.length; index++)
{
if (rain[index] > highest)
highest = rain[index];
highestMonth = index;
}
return highestMonth;
}

Standard Deviation java, proper equation

This is all my code. I am having problems with the standard deviation formula.
I run the program with these values:
Number of items: 5
Items: 16 25 81 80 24
I'm supposed to get this output:
Average:    45.20
Std Dev:    32.41
Less than Avg: 3
Array is not in sorted order
Instead, I get this output:
Array is not in sorted order
Average: 45.20
Std Dev: 55.60
Less than Avg: 3
import java.text.DecimalFormat;
import java.util.Scanner;
public class array {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ("#.00");
System.out.println("How many values do you want?");
int num = input.nextInt();
if (num< 1 || num > 100)
{
System.out.println("Error");
System.exit(0);
}
int[] array= valueArray(input, num);
double o= average(num, array);
double standdev = getStdDev(array, num);
int lessThanAvg = lessAvg ( array, num, o );
boolean sorted=isArraySorted(array, num);
System.out.println("Average: " + df.format(o));
System.out.println("Std Dev: " + df.format(standdev));
System.out.println("Less than Avg: " + lessThanAvg);
}
public static int[] valueArray (Scanner input, int num )
{
int[] values = new int[100];
System.out.println("What numbers do you want to put in?");
for (int j = 0; j < num; j++)
{
values[j]=input.nextInt();
}
return values;
}
public static double average ( int num ,int[] values)
{
double avg=0.0;
for (int i = 0; i < num; i++)
{
avg = avg+values[i];
}
return avg/num;
}
public static double getStdDev (int [] values, int num)
{
double avg = 0.0;
double sum = 0 ;
for (int i = 0; i < num - 1; i++)
{
sum = Math.sqrt ((Math.pow((values[i]-avg),2) + Math.pow((values[num-1]),2)) / num-1);
}
return sum;
}
public static int lessAvg ( int [] values, int num, double avg )
{
int counter = 0;
for (int i = 0; i < num; i++ )
{
if (values[i] < avg)
{
counter = counter + 1;
}
}
return counter;
}
public static boolean isArraySorted (int [] values, int num)
{
for (int i = 0; i < num - 2; i++)
{
if (values[i]>values[i+1])
{
System.out.println("Array is not in sorted order");
return false;
}
}
System.out.println("Array is in sorted order");
return true;
}
}
to get the standard deviation
find out the mean.
Then for each number of your array subtract the Mean and square the
result.
Then work out the mean of those squared differences
find the square root of that.
For reference you can look at this Post

Need a sort method in Java with user input using the scanner class [duplicate]

This question already has answers here:
Need Java array help using scanner class to output an average and sort method
(4 answers)
Closed 6 years ago.
I have a method to output the highest value, lowest value, average value and I need a sort method. I have tried to put what is called a "bubble method" but it isn't working out. Anyone know other sort methods I can use?
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
//System.out.println ( "\nLargest " + max (1, 3, 5) );
System.out.println("sorting" + sort(array));
System.out.println("The highest number in the array is " + max(array));
System.out.println("The smallest number in the array is " + min(array));
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static int sort(int[] arg) {
for (int i = 1; i < arg.length - 1; i++) {
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
int arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
return arrange;
}
public static int max(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int largest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] > largest) {
largest = arg[i];
}
}
return largest;
}
public static int min(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int smallest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] < smallest) {
smallest = arg[i];
}
}
return smallest;
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
}
There are many other sort methods you can use. The one you were trying to use is called "Bubble Sort" and is very expensive on large data sets unless they are somewhat ordered. I would recommend using selection sort or insertion sort for what you are trying to accomplish.
Here is a link to the many sorting algorithms you can implement: Sorting Algorithms
Here are some animations showing the process of these sorts (Highly recommend you look at these before implementing your algorithm):
Helpful animations
You can use any sorting method as your convenient and according to your requirement. After sorted the array you can easily pick up the minimum and maximum value from the sorted array, first element and the last element of the array.
For calculate the average you have to use separate method as you used or you can use static variable to calculate the total inside the sorting method.
Refer this code.
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
sin.close();
System.out.println("sorting");
printArray(array); //Before sort
sort(array);
printArray(array); //After sort
System.out.println("The highest number in the array is " + array[array.length - 1]);
System.out.println("The smallest number in the array is " + array[0]);
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static void sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++)
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
public static void printArray(int[] arr) {
for (int value : arr) {
// print elements according to your convenient
System.out.println(value);
}
}
To print the array you have traversal through the array. See Above code method.

Not ignoring a value?

import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.

Number Analysis Program

I am in a beginner Java class and just learning the concept of arrays. We have to use comments to denote the code.
I am trying to make a program that asks the user to enter 20 numbers, stores them in an array and then calculates and displays: the lowest number, the highest number, the total of the numbers and the average of the numbers.
I have a ton of errors when running it through jGrasp and am unsure how to fix them.
Any advice?
public class NumberAnalysisProgram
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
//A constant for the array size
final int SIZE = 20;
//Declare an array to hold the numbers entered by the user
int[] numbers = new int[SIZE];
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
//Declare variable to hold the total
int sum;
//Declare a variable to hold the average
double average;
//Declare a counting variable to use in the loops
int index = 0;
//Explain the program
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers,
and the average.");
//Get the numbers from the user
for (int i = 0; i< numbers.length; i++)
{
System.out.print("Please enter 20 numbers, each seperated by a space: ");
numbers[i] = input.nextInt();
}
//Call a method to calculate the lowest and highest numbers
getLowHigh(numbers);
//Display the lowest and highest numbers
System.out.println("The lowest number is: " + lowest);
System.out.println("The highest number is: " + highest);
//Call a method to calculate the total of the numbers
sum = getTotal(numbers);
//Display the sum/total of the numbers
System.out.println("The total of these numbers are: " + sum);
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
//Display the average of the numbers
System.out.println("The average of these numbers are: " + average);
}
//Method getLowHigh
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
//Method getTotal
public static int getTotal(int[] array)
{
//Loop counter variable
int index;
//Accumulator variable initialized to 0
int total = 0;
//Pull in the numbers from the main method to calculate the total
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
return total;
}
//Method getAverage
public static int getAverage(int[] array)
{
//Loop counter variable
int index;
//Pull in the sum and the numbers from the main method to calculate the average
for(index = 0; index < numbers.length; index++)
{
average = sum / number[index];
}
return average;
}
}
The first problem I can see is that in all of the methods, you never used the arguments. You used a different array, which doesn't exist within those methods.
The second problem is that you're trying to return two values from one method. You can only return one value from a method. So you have to get rid of "return highest;" and make a copy of the method in which there is no "return lowest;", and use each where needed.
The third thing I see (although it isn't causing any errors) is that you could shorten the code by saying
int total = 0;
for(int index = 0; index < numbers.length; index++)
{
total += number[index];
}
instead of
int index;
int total = 0;
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
For starters, the below code is trying to initialize variables to array values that don't exist… These should be removed entirely.
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
There will also be an error with these in the code below because you're not passing them to the function therefore it doesn't exist within this scope.
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
You are also supplying 2 parameters for a function that only calls for one. See below:
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
I think that this is more clean:
public class Main {
public static final int SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
Double total = 0d;
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers, and the average.");
// Get the numbers from the user
System.out.print("Please enter 20 numbers, each seperated by a space: ");
for (int i = 0; i < SIZE; i++) {
Integer currInput = input.nextInt();
numbers.add(currInput);
total += currInput;
}
System.out.println("The lowest number is: " + Collections.min(numbers));
System.out.println("The highest number is: " + Collections.max(numbers));
System.out.println("The total of these numbers are: " + total);
System.out.println("The average of these numbers are: " + (total / SIZE));
}
}
Hope it helps :]

Categories