Thursday, January 30, 2020

Nguyen-PM-40 mins - Open Lab

I worked on a code that can print out the array of list numbers from copying inputs from user, also calculate its range, average and determine is it a increasing or decreasing or unsorted order.
But I have trouble at determining sorting order.
 I used "for loop", if else statements, and math methods.

import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;

class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
//Set Variable-----------------------------------------
int count = 0;
double sum = 0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;

//Set up-----------------------------------------------
System.out.println("How long do you want the array?");
int num = scan.nextInt();
if (num<0)
{
System.out.println("Not a valid length!");
}
else
{
double[] array = new double [num];

for (int i = 0; i < num; i++)
{
System.out.println("Enter a number:");
double x = scan.nextDouble();
array[i] = x;
sum += x;
count++;
}
//Find the smallest num in array-------------------------
for (int u = 0; u < num; u++)
{
if (min > array[u])
{
min = array[u];
}
}
//Find the largest num in array-------------------------
for (int a = 0; a < num; a++)
{
if (max < array[a])
{
max = array[a];
}
}
System.out.print("Your array is { ");
//Print out the array----------------------------------
for (int e = 0; e < num; e++)
{
System.out.print(array[e] + ", ");
}
System.out.println("}");
System.out.println("The average is " +(sum/count));
System.out.println("The range is " + (max-min));
//Sorted order array-----------------------------------
for (int z = 0; z < (num-1); z++)
{
if ( array[z] > array[z+1])
{
System.out.println("The array is sorted in decreasing order");
}
else if ( array[z] < array[z+1])
{
System.out.println("The array is sorted in increasing order");
}
else
{
System.out.println("The array is unsorted");
}
}
}
}
}

No comments:

Post a Comment