1

I've been trying to get this quiz to work for a while now. Everything seems to be working up until I try to count how many questions the user got right. It seems as though the "correct" variable isn't getting added onto when it should be. It always displays 0.

public class PresidentQuiz {

    public static void main(String[] args) {
        Integer correct = 0;
        Map<Integer, String> president1 = new HashMap<Integer, String>();
        president1.put(35, "Kennedy");
        president1.put(36, "Johnson");
        president1.put(37, "Nixon");
        president1.put(38, "Ford");
        president1.put(39, "Carter");
        president1.put(40, "Reagan");
        president1.put(41, "George Bush");
        president1.put(42, "Clinton");
        president1.put(43, "George W Bush");
        president1.put(44, "Obama");
        System.out.println("Size of map: " + president1.size());

        Map<Integer, String> president2 = new TreeMap<Integer, String>(president1); 
        Set set1 = president2.entrySet();
        Iterator iterator1 = set1.iterator();
        while(iterator1.hasNext()) {
             Map.Entry me = (Map.Entry)iterator1.next();
             System.out.print("President #" + me.getKey() + ": ");
             System.out.println(me.getValue());
            }
        HashSet<Integer> randint = new HashSet<Integer>();
        while(randint.size() < 5) {
            randint.add((int) (Math.random() * ((44 - 35) + 1) + 35));
        }
        System.out.println();
        System.out.println("Presidents Quiz");
        System.out.println();
        String pres = null;
        Iterator<Integer> iterator2 = randint.iterator();
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in); 
        while(iterator2.hasNext()) {
            System.out.println("Who was president #" + iterator2.next() + "?");
            pres = input.next();
        }
        while(iterator2.hasNext()) {
            String name = president1.get(iterator2.next());
            if (name == pres) {
                correct += 1;
            }
        }
        // Print correct score
        System.out.println("Your score was " + correct);
        System.out.println();
        // Want to sort names in alphabetical order
        System.out.println("Here are the last 10 presidents in alphabetical order:");

        }
    }
dungo
  • 103
  • 1
  • 2
  • 13

1 Answers1

1

You cant compare strings using ==. You must use equals(). See How do I compare strings in Java?

Community
  • 1
  • 1
ar34z
  • 2,609
  • 2
  • 24
  • 37