Skip to content
Advertisement

Java picks any random number as the correct answer

I want to develop a “periodic table tester” which asks you the atomic number of any random element. If you answer wrong, it will tell you the correct answer.
Here’s my code:

import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;

class element {
  public static void main(String[] args) {
    // create an object of Scanner class
    Scanner input = new Scanner(System.in);
    // creating an array of elements (only first thirty for now)
    String[] elements = {"hydrogen", "helium", "lithium", "berylium", "boron", "carbon", "nitrogen", "oxygen", "flourine", "neon", "sodium", "magnesium", "aluminium", "silicon", "phosphorus", "sulphur", "chlorine", "argon", "potassium", "calcium", "scandium", "titanium", "vandium", "chromium", "manganese", "iron", "cobalt", "nickel", "copper", "zinc"};
    // pick a random element
    Random random = new Random();
    int pickRandom = random.nextInt(elements.length);
    String randomElement = elements[pickRandom];
    // ask the question
    System.out.println("What is the atomic number of "+ randomElement + "?");
    System.out.print("Your answer: ");
    // ask for input
    int yourAnswer = input.nextInt();
    // check the answer
    int result = Arrays.binarySearch(elements, randomElement);
    int recievedInput = yourAnswer - 1;
    int correctAnswer = result + 1;
    if (recievedInput == result) {
      System.out.println("Correct Answer!");
    } else {
      System.out.println("Sorry, but you need some more practice. The correct answer is " + correctAnswer + ".");
    }
    // close the object with Scanner class
    input.close();
  }
}

Its output should be like

$ java element
What is the atomic number of nitrogen?
Your answer: 7
Correct Answer!

$ java element
What is the atomic number of helium?
Your answer: 5
Sorry, but you need some more practice. The correct answer is 2.

But, it’s like:

$ java element
What is the atomic number of oxygen?
Your answer: 8
Sorry, but you need some more practice. The correct answer is -10.

$ java element
What is the atomic number of chromium?
Your answer: 0
Correct Answer!

$ java element
What is the atomic number of lithium?
Your answer: 3
Correct Answer!

How should I solve the problem?

Advertisement

Answer

You’re using Arrays.binarySearch() on the wrong type of data set. It needs to take a sorted input to work properly.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement