Unfortunately the code below doesn't totally work. I got mixed up and I ran out of time to fix my errors. But you can sort of see the logic (sort of) behind the code.
//Christopher Smith
//CSC 15
//Lab 10b: more subroutines
import java.util.Scanner; //for keyboard
import java.util.Random; //for random number gen
public class lab10b {
public static void main (String[] args){
Scanner kb = new Scanner(System.in);
int pick, answer;
int[] arr = new int[20];
while (true)
{
System.out.println("");
System.out.println("======Menu=======");
System.out.println("Pick A Number");
System.out.println("0: Quit");
System.out.println("1: Generate a random array");
System.out.println("2:Show the array");
System.out.println("3:Show Sum");
System.out.println("4:Show Min Value");
System.out.println("5:Show Max Value");
System.out.println("6:Show Avg of Array");
System.out.println("7:Sort array");
System.out.println("");
System.out.println("Selection: ");
int menNum = kb.nextInt();
System.out.println("");
if (pick==0) return; //quits program
else if (pick==1)randomizeArray(arr);
else if (pick==2)showArray(arr);
else if (pick==3)
{
answer = arraySum(arr);
System.out.println("Sum of array is "+answer);
}
else if (pick==4)
{
answer = arrayMin( arr );
System.out.println("Min is " + answer);
}
else if (pick==5)
{
answer = arrayMax( arr );
System.out.println("Max is " + answer);
}
else if (pick==6)
{
answer = arrayAvg(arr);
System.out.println("AVG is "+answer);
}
else if (pick==7)
{
sortArray(arr);
System.out.println("Sorted");
}
else
{
System.out.println("Wrong Number, Pick Another");
}
}
}
public static void randomizeArray(int[] arr){
int i;
for (i=0; i<arr.length; i++) //loop to grab numbers
{
arr[i] = arr.nextInt(20);//random number in i spot
}
}
public static void showArray(int[] arr){
int i;
for (i=0; i<arr.length;i++)
{
System.out.print(arr[i]);
}
}
public static int arraySum(int[] arr){
int sum = 0;
int i;
for (i=0;i<arr.length;i++)
{
sum=sum+arr[i];
}
System.out.print(sum);
}
public static int arrayMin(int[] arr){
int min = 99999;
int i;
for (i=0;i<arr.length;i++)
{
if (arr[i]<min)
{
min=arr[i];
}
}
System.out.print(min);
}
public static int arrayMax(int[] arr){
int max = 0;
int i;
for (i=0;i<arr.length;i++)
{
if (arr[i]>max)
{
max=arr[i];
}
}
System.out.print(max);
}
public static int arrayAvg(int[] arr){
arraySum(sum);
int avg;
avg=sum/arr.length;
System.out.print(avg);
}
public static void sortArray(int[] arr){
int i, j,temp,min;
for (i=0; i<=arr.length; i++)
{
min = i;
for (int j = i+1; j<=arr.length; j++)
{
if (arr[j] < arr[min])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
System.out.println();
}
}
}
No comments:
Post a Comment