I'm working on a program where I need to have the user enter the size of the array and then enter the numbers to be stored in the array. If the user enters in -99999 the program quit. I also need to display the sum of numbers enter into the array and the average of the numbers. Later on I need to display all of the values enter into the array, but not right now. I can get the sum and average and the size of the array, but I'm having trouble getting the values to be stored into the array. I would appreciate any help.

Sincerely yours;

jdm

package hw3;

//Libraries
import javax.swing.*;
import java.util.*;

//Declairng class
public class Main { 
   
    //declaring main with arguments
    public static void main(String[] args) {

        double    Average,
                  sum,
                  difference,
                  temp;

        sum = 0.0;
        Average = 0.0;
        difference = 0.0;
        temp = 0.0;
        int size = 0;
        double myArray[ ] = new double[size];
        int a = 0;

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the size of the array:  ");
        size = scanner.nextInt();
        
        System.out.println("Size = " + size);
        System.out.print("Enter numbers:  ");
        temp = scanner.nextDouble();
        a++;

         for (int i = a; i < size; i++)
         {
             if (i == size)
                 break;
             else if (temp == -99999.0)
                 break;

             myArray[i] = temp;
             System.out.println("temp = " + temp);
             sum += temp;
             System.out.print("Enter numbers:  ");
             temp = scanner.nextDouble();

             System.out.println("i = " + i);
            // myArray[i] = temp;

         }
        if (sum <= 0){
            sum = sum + temp;
            sum = sum + -99999.0;
        }
        else if (sum >= 0){
            sum = sum + temp;}
        System.out.println("The sum:  " + sum);
        Average = sum / size;
        System.out.println("The Average is:  " + Average);

       //System.out.format( "Average Rainfall:%5.2f\n\n", Average );

      //  for (int i = 0; i < size; i++) {

         //   System.out.println("array:  " + myArray[size]);
            //difference between the monthly and annual averages
            //difference = Math.abs( myArray[i] - Average );
            //System.out.format("%15.2f\n", difference);
       // }
    }
}

Recommended Answers

All 3 Replies

Member Avatar for ztini

As a console UI, it should be reasonable to assume that a) the user wants to quit before they start entering data or b) after completion. Having this set to quit in the middle based on array size is bad form. Your UI does not include some sort of initial menu where the user selects an option (1 - Sum/Avg Array, 2 - Quit), it dives right it. That said, it should probably only prompt the user to quit at the end.

On variables, don't declare variables that can be replicated through an equation. For instance, you should declare a sum variable because you need to go through several array slots to arrive at this data. On the other hand, the average can be replicated from doing the sum / array.length; hence no need to store it.

Additionally, you only want to declare imports you're actually using. With that, you only want to include the actual class you're importing, not the entire package.

For instance:

import java.util.Scanner;

public class ArrayMath { 

	private int[] array;
	
	public ArrayMath() {
		displayMenu();
	}
	
	private void displayMenu() {
		Scanner in = new Scanner(System.in);
		
		System.out.print("Array Size: ");
		array = new int[in.nextInt()];
		
		System.out.println("Values: ");
		for (int i = 0; i < array.length; i++)
			array[i] = in.nextInt();
		
		int sum = 0;
		for (int i : array)
			sum += i;
		System.out.println("Sum: " + sum);
		System.out.println("Avg: " + sum / (double) array.length);
		
		System.out.println();
		System.out.print("Again? (Y/N) ");
		String response = in.next();
		System.out.println();
		
		if (response.charAt(0) != 'Y' && response.charAt(0) != 'y')
			return;
		displayMenu();		
	}
	
	public static void main(String[] args) {
		new ArrayMath();
	}
}

Console:

Array Size: 5
Values: 
1
2
3
4
5
Sum: 15
Avg: 3.0

Again? (Y/N) y

Array Size: 3
Values: 
7
5
3
Sum: 15
Avg: 5.0

Again? (Y/N) n

Thanks for the help, but I got it to work. I just have one more thing to do and I would appreciate the help. Here is what I have to do:

display in two columns on the output screen (using System.out)
the headings Numbers and Distance From Mean. (Mean and average are the same.) Use columns of width 20 for each.
Underneath these headings, display the numbers and their distances from the mean. All numbers should have exactly two decimal places
and should be right-justified in the columns.

package hw3;

//Libraries
import javax.swing.*;
import java.util.*;
import java.text.*;



public class Main {

/**
* @param args the command line arguments
*/


public static void main(String[] args)
{

JFrame IOA;
IOA = new JFrame();
IOA.setSize(500,500);
IOA.setVisible(true);
try {Thread.sleep(200);} catch (Exception e) {}

int size = 100;
double numArray[ ] = new double[size];
final int sentinel = -99999;
int count = 0;
int sum = 0;
double average = 0;
// double distFromMean= 0;

Scanner scanner = new Scanner(System.in);//Declare a new scanner that is taking user input.
System.out.print("Please enter upto 100 numbers(enter -99999 to stop) ");

for (int i = 0; i< size; i++)
{
System.out.print("#" + (i+1));
numArray[i] = scanner.nextDouble( );
if (numArray[i] == sentinel )
break;

count++;
sum += numArray[i]; //Adding up the total for all numbers in numArray.
}

average = sum/count;


// Declare a new Decimal Format to output data to two decimal places.
DecimalFormat df = new DecimalFormat("0.00");
//Display average of Numbers.

JOptionPane.showMessageDialog(null, "The average is " +df.format(average));


//help here and on
// display in two columns on the output screen (using System.out) Columns of width 20.
System.out.format("%20s%40s","Number", "Distance From Mean");

//For loop to print out the numbers from numArray and their distance from the mean/average.
for(int i = 0; i<=count; i++){
// distFromMean = numArray[i]-average;
System.out.format("%20.2f%35.2f", numArray[i], Math.abs(numArray[i] - average));
}
}

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.