Question: In java, fix the code so 1.) User can only input integers 1-10, and if any other integer then it should throw an exception, print

In java, fix the code so

1.) User can only input integers 1-10, and if any other integer then it should throw an exception, print out invalid input please try again, and allow the user to reinput.

2.) If user inputs random stirng then it should do the same above ^ except for R to refill array and q to quit the program.

import java.util.*;

public class KSmallTester {public final static int SIZE_OF_ARRAY = 10;

public final static String PROMPT = "Please enter an integer k, 1<=k<=" +

SIZE_OF_ARRAY + ", or 'R' to refill the array: ";

public static void printArray(int[] array) {

System.out.println("");

System.out.print("array = [");

for (int i=0; i < SIZE_OF_ARRAY-1; i++)

System.out.print(""+ array[i]+" | ");

System.out.println(""+ array[SIZE_OF_ARRAY-1]+"]");

System.out.println("-------------------------------------------------"

+ "-------------------");

}

public static void randFillArray(int[] array) {

Random random = new Random();

for (int i=0; i < SIZE_OF_ARRAY; i++)

array[i] = random.nextInt(100);

}

public static void main(String argv[]) {

int k = 1, kthSmallest = 0;

int[] array = new int[SIZE_OF_ARRAY];

int[] arrayTmp = new int[SIZE_OF_ARRAY];

randFillArray(array);

printArray(array);

// ToDo: Read input k and print out the k-th smallest item of the array.

// Note that your program should allow finding k-th smallest item from an array

// continuously (i.e., more than once) , refilling the array, and exiting the

// program when typing in "Q" or "q".

String choice = null;

Scanner sc = new Scanner(System.in);

do

{

System.out.println(PROMPT);

choice =sc.nextLine();

if (choice.equalsIgnoreCase("R")) {

randFillArray(array);

printArray(array);

} else if (choice.equalsIgnoreCase("q")) {

System.out.println("Thank you for using");

System.exit(0);

}else {

int kth = Integer.parseInt(choice);

//Create a deep copy of array

for (int i = 0; i < SIZE_OF_ARRAY;i++) {

arrayTmp[i] = array[i];

}

int kthSmall = KthSmallest.kSmall(kth, arrayTmp, 0, SIZE_OF_ARRAY -1);

System.out.println("Kth Smallest Elemnt : " + kthSmall);

}

}

while(choice!=null);

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!