Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in java that will prompt the user to enter a number, n, of men.

ID: 649657 • Letter: W

Question

Write a program in java that will prompt the user to enter a number, n, of men. Fill a LinkedList with n Integer objects numbered 1, 2, , n. (Hint: The Integer value will be equal to the man's position in the original list.).use the Collections class has an algorithm called rotate(List<?> list, int distance) which can be used to rotate a list left or right to eliminate every other Integer beginning with the Integer in the second position. Remember that if you remove an item in the middle of the list, the items which follow it are shifted forward in the list.Continue eliminating integers until a single Integer is left. Print the list for each step in this process and the survivor's position.

Explanation / Answer

import java.util.*;

public class LinkedList {
   public static void main(String[] args){
       Scanner s=new Scanner(System.in);
       int n;
       System.out.println("Enter n: ");
       n=s.nextInt();   //accept n from user input
       List<Integer> numbers = new ArrayList<Integer>();   //declare linked list of integer
       for(int i=1;i<=n;i++){
           numbers.add(new Integer(i));   //fill the list of integers
       }
       System.out.println("List : "+Arrays.toString(numbers.toArray()));   //display the list
       for(int i=1;n>1;){
           Collections.rotate(numbers, 2);   //rotate the list from element in the 2nd position
           System.out.println("Rotated the list from second position: "+Arrays.toString(numbers.toArray())); //display list after rotation
           numbers.remove(n/2);   //calculate the middle element in the list
           System.out.println("Removed the middle element: "+Arrays.toString(numbers.toArray()));   //remove the middle element from the list
           n--;   //decrease the number of items in the list
       }         
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote