Directions Points The file must be called YourNameChapter9Prog.java Example: Ken
ID: 3540878 • 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 outputsExplanation / Answer
I figured it out. I changed it up a bit but it works for me now.
import java.util.Arrays;
import java.util.Scanner;
public class YourNameProg9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int [] arr=new int[100];
int counter=0;
int occupiedrooms=0;
System.out.println("Please enter an occupied hotel room number, -1 to quit ");
do{
occupiedrooms = sc.nextInt();
if(occupiedrooms==-1)
break;
if(occupiedrooms>0)
arr[counter++]=occupiedrooms;
}while(occupiedrooms !=-1);
// sort using java API
int [] temparr=new int[counter];
for(int i=0;i<counter;i++){
temparr[i] = arr[i];
}
arr = temparr;
Arrays.sort(arr);
//binary search.
int low=0;
int mid;
int high = counter-1;
int status=0;
System.out.println("Please enter a hotel room number ");
occupiedrooms = sc.nextInt();
while(low<high){
if(arr[low]==occupiedrooms){
System.out.println("This room is Occupied");
status=1;
break;
}
else if(arr[high]==occupiedrooms){
System.out.println("This room is Occupied");
status=1;
break;
}
mid = low+high/2;
if(arr[mid]==occupiedrooms){
System.out.println("This room is Occupied");
status=1;
break;
}
else if(arr[mid]<occupiedrooms){
low=mid;
}
else if(arr[mid]<occupiedrooms){
high = mid;
}
else if(status==0){
System.out.println("This room is Unoccupied");
break;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.