Java: How To "Rank" Items In An ArrayList Filled With User-Inputed Items?

82 Views Asked by At

I'm creating a Java program that allows a user to enter in a set of related items and then rank them from greatest to least. The first part of the code allows a user to enter as many items as they want, and unless they type "STOP," the user's input gets stored in an ArrayList. For example:

`Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.

Star Wars

Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.

Harry Potter

Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.

The Lord of the Rings

Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.

STOP`

The expected result should be:

You have entered: Star Wars Harry Potter The Lord of the Rings

This part of the program is finished, but I'm really struggling to figure out the next step - the actual ranking. Because there is not a limit on what can be entered into the ArrayList, I'm unsure as to how to direct the program to ranking the items entered. I know that I want to prompt the user to choose between the different items entered ("Do you prefer Item A or Item B?"), but I'm not sure how to go about doing it when the ArrayList doesn't have a limit on what can be entered in. Could I get some direction?

`//Ranking.java is a program designed to prompt user for a list of related items //and stores them in an array. The program will then prompt the users to rank //those items from greatest to least then prints out their ranking

//import Scanner and ArrayList
import java.util.*;

//declare class
public class Ranking {

    //declare main method
    public static void main(String[] args) {
        
        //initialize scanner
        Scanner input = new Scanner(System.in);
        
        //create ArrayList to store items
        ArrayList<String> items = new ArrayList<String>();
        
        //introduction
        System.out.println("Welcome to Ranking.java!");
        
        //while loop that repeats the prompt unless the user enters "STOP"
        while(true) {
            //prompt
            System.out.print("\nPlease enter an item you wish to add to the ranking list, "
                    + "or type 'STOP' to end the program.\n>> ");

            //stored in item variable
            String item = input.nextLine();
            
            //if item equals "STOP," program breaks and prints out the list of items entered
            if(item.equals("STOP")) {
                System.out.println("\nYou have entered:");
                for(int i = 0; i < items.size(); i++) {
                    System.out.println(items.get(i));
                }
                break;
            }
            //otherwise it adds to the ArrayList
            else {
                items.add(item);
            }
        }
        
        ArrayList<String> itemsRanked = new ArrayList<String>();
        
        //ranking introduction
        System.out.println("\nYou may now rank the following from greatest to least.\n");
        
        
    }
}
1

There are 1 best solutions below

0
Gilbert Le Blanc On

I modified your code and added some code. Here's one of my test results.

Welcome to Ranking.java!

Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.
>> Item 1
Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.
>> Item 2
Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.
>> Item 3
Please enter an item you wish to add to the ranking list, or type 'STOP' to end the program.
>> stop

For item Item 1, enter a ranking from 1 to 3
>> 3
For item Item 2, enter a ranking from 1 to 3
>> 2
For item Item 3, enter a ranking from 1 to 3
>> 1

You ranked Item 3 as 1
You ranked Item 2 as 2
You ranked Item 1 as 3

The first thing I did was create a RankItem class to hold an int rank and a String item.

public class RankItem {
    
    private int rank;
    
    private final String item;

    public RankItem(String item) {
        this.item = item;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }

    public String getItem() {
        return item;
    }
    
}

Next, I took your code and divided it up into four methods. The first method reads the items, the second method reads the ranks, the third method sorts the List into rank, alphabetical order, and the final method prints the sorted List.

Divide and conquer.

The sort sorts the List in rank, alphabetical order in the event the user enters multiple similar ranks. The rank values can be any positive int.

Here's the complete runnable code. I made the additional class an inner class so I could post the code as one block.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

// Ranking.java is a program designed to prompt user for a list of related items 
// and stores them in an array. The program will then prompt the users to rank 
// those items from greatest to least then prints out their ranking.

public class RankingItems {

    public static void main(String[] args) {
        RankingItems ri = new RankingItems();
        ri.processItems();
    }

    private final List<RankItem> rankItems;

    private final Scanner input;

    public RankingItems() {
        this.rankItems = new ArrayList<>();
        this.input = new Scanner(System.in);
    }

    public void processItems() {
        readItems();
        rankItems();
        sortItems();
        writeItems();
    }

    private void readItems() {
        System.out.println("Welcome to Ranking.java!");
        System.out.println();
        while (true) {
            // prompt
            System.out.println("Please enter an item you wish to "
                    + "add to the ranking list, "
                    + "or type 'STOP' to end the program.");
            System.out.print(">> ");
            String item = input.nextLine();
            if (item.equalsIgnoreCase("STOP")) {
                return;
            } else {
                rankItems.add(new RankItem(item));
            }
        }
    }

    private void rankItems() {
        System.out.println();
        for (RankItem rankItem : rankItems) {
            int rank = -1;
            while (rank < 0) {
                System.out.println("For item " + rankItem.getItem()
                        + ", enter a ranking from 1 to " + rankItems.size());
                System.out.print(">> ");
                String rankString = input.nextLine();
                try {
                    rank = Integer.valueOf(rankString);
                    rankItem.setRank(rank);
                } catch (NumberFormatException e) {
                    continue;
                }
            }
        }
    }

    private void sortItems() {
        Collections.sort(rankItems, new Comparator<RankItem>() {
            @Override
            public int compare(RankItem o1, RankItem o2) {
                if (o1.getRank() > o2.getRank()) {
                    return 1;
                } else if (o1.getRank() < o2.getRank()) {
                    return -1;
                } else {
                    return o1.getItem().compareTo(o2.getItem());
                }
            }
        });
    }

    private void writeItems() {
        System.out.println();
        for (RankItem rankItem : rankItems) {
            System.out.println("You ranked " + rankItem.getItem() + " as "
                    + rankItem.getRank());
        }
    }

    public class RankItem {

        private int rank;

        private final String item;

        public RankItem(String item) {
            this.item = item;
        }

        public int getRank() {
            return rank;
        }

        public void setRank(int rank) {
            this.rank = rank;
        }

        public String getItem() {
            return item;
        }

    }

}