Directions Points The file must be called YourNameChapter9Prog.java Example: Ken
ID: 3545092 • Letter: D
Question
Directions Points
The file must be called YourNameChapter9Prog.java
Example: KenDeweyChapter9.java
Ensure you include ALL files required to make your program compile and run. I would like
to see your .java files only.
Chapter 9 Class File
Write a program that reads input for occupied hotel rooms and using the Java API, sorts
the rooms, then search for a particular room to see if it is occupied or not.
The program will utilize a loop to get input for occupied hotel rooms until a sentinel value of
your choosing is entered.
The program should utilize the Java API to sort the array of rooms.
The program then asks for input for a particular room number.
Utilize a binary search to search for a particular room and outputs
Explanation / Answer
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ABCReddyChapter9Prog
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[],i,j;
List<Integer> l1 = new ArrayList<Integer>();
System.out.println("Enter the occupied rooms list: ");
Scanner in = new Scanner(System.in);
while(true){
i= in.nextInt();
if(i!=-1){
l1.add(i);
}else{
break;
} // close of else block
} // close of while block
System.out.println("Please enter a room to search for:");
j = in.nextInt();
n = l1.size();
array = new int[n];
for(int k=0;k<n;k++){
array[k] = l1.get(k);
}
search = j;
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println("This room is Occupied!");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last ){
System.out.println("This room is Unoccupied!");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.