Number Analysis Program - java

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 :]

Related

Finding the Max Value of the last row of a 2D array

I'm trying to find the maximum value of the last column and i need to print it out. I tried using the Double.max(); method but it doesn't work for the specific array and I wanted to create an array for the 13th column but it won't let me.
import java.lang.reflect.Array;
public class LabMidterm3 {
public static void main(String[] args) {
double[][] myArray =new double [4][13];
double row = myArray.length;
double column = myArray[0].length;
for (int i=0; i<row;i++){
int sum =0;
for(int j=0; j<column;j++){
double random = (int)(Math.random()*7.0);
myArray[i][j] = random;
sum+=myArray[i][j];
System.out.print(myArray[i][j] + ", ");
double max = Array.getDouble(myArray, 13);
if(j==13){
System.out.print("The max value is: " + max);
}
}
double rowAverage= sum/column;
if(i==1){
System.out.println();
System.out.print("The average is: " +rowAverage);
System.out.println();
}
System.out.println();
}
}
Since you are calculating (and storing) double values, don't cast the random to an int. Next, initialize max to some non-present value guaranteed to be smaller than any value present (like -∞). Then use Math.max(double, double) to update it while you iterate the row. And you can use Arrays.toString(double[]) to print your row. Finally, print the average and max after you populate the array. Something like
double sum = 0;
double max = Double.NEGATIVE_INFINITY;
for (int j = 0; j < column; j++) {
myArray[i][j] = Math.random() * 7.0;
max = Math.max(max, myArray[i][j]);
sum += myArray[i][j];
}
System.out.println(Arrays.toString(myArray[i]));
double rowAverage = sum / column;
if (i == 1) {
System.out.println("The average is: " + rowAverage);
System.out.println("The max is: " + max);
}

how can i save input from joptionpane as an array?

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.

incompatible types - double to int?

Java seems to think that I am attempting to convert or perform some kind of action on one of my double variables. I get the error message
average2.java:23: error: incompatible types: possible lossy
conversion from double to int scores[count++]=score;
I am really confused in that I have not declared anything as an integer thus far, - every variable is a double because I expect to have some decimals. Below is my code :
public static void main (String [] args)
{
double numOf;
double lowest = 100;
double count = 0;
double sum = 0;
double average = 0;
double score;
double scores[] = new double[100]; //[IO.readDouble("Enter Scores, Enter -1 to Quit")];
while ((count <100) &&(( score =IO.readDouble("Enter Scores, (-1 to Quit")) > 0));
{
scores[count++]=score;
}
//This section obtains the highest number that was entered`
double max = scores[0];
for (double i=0; i<scores.length; i++)
if(max < scores[i])max =scores[i];
System.out.println("Maximum is " + max);
// This section obtains the lowest score entered
double min = scores[0];
for (int i=0; i<scores.length; i++)
if (min > scores[i]) min = scores [i];
int sumOf =0;
for (int i=0; i < scores.length; i++)
{
sumOf += scores[i];
}
System.out.println("The sum of all scores is " + sumOf);
System.out.println("Minimum is " + min);
count = count + 1;
average = (sumOf/scores.length);
System.out.println("Average is " + average);
} //end main
} //end class
The error refers to the count variable, which is a double. But ints are valid indices for an array. The error results from using a double as an index where an int was expected for the index.
Declare count to be an int.
You should also declare i to be an int in the first for loop, for the same reason.

Create an array based on a range of values given by the user

What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}

Average Random Integers

I am trying to write a program that takes an integer as command-line argument, uses random to print N uniform random values between 0 and 1, and then prints their average value.
I'm not sure what arguments to put in the while loop so that random integers are repeated n times, n being the number from the user indicating the number of integers the random has to generate.
Any help would be appreciated.
enter code here
public class UniformRandomNumbers1 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
double total = 0.0; //(The sum of n, numbers)
for (i = 1; i <= n; i++) {
double rand = Math.random(); //(Random number between 0 & 1)
total += rand; // Increment total by rand
System.out.println(i + " = " + rand); // Prints value of n & corresponding double value
}
double average = total / n; // Calculates average of n numbers
System.out.println("Average = " + average); // Prints average of n numbers, Can i get an up vote? :) plz
}
}
if you just need to execute a loop a specific number of times, I'd use a for loop
The following loop will iterate exactly n times, and It's what I personally use when I need to do something exactly n times.
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
under the assumption that your PRNG is behaving correcly you just need this:
main()
{
printf("\n0.5");
exit(0);
}
that's for N sufficiently large... computed in constant time. otherwise use the moving average formula:
http://en.wikipedia.org/wiki/Moving_average
which requires only O(1) memory space instead of the naive O(N) approach
here the cut&paste java code:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}

Categories