Hi there. I am a beginner and I can't seem to figure out what is wrong with my code.
I am trying to write a program that will ask a user to enter a number between 1 and 10,000 and then report whether the number is prime. But when I test it, it keeps telling me that every single number is composite, even though it actually is prime. It is for an assignment for school so I am not allowed to use any more advanced java than what I have here.
The program is supposed to:
Read the numbers from a file
Store them in an array
Implement a the binary search method to search for the number entered by the user.
import java.util.Scanner; import java.io.*; public class Primes { public static void main(String[] args) throws IOException { File inFile = new File("primes.txt"); Scanner input = new Scanner(inFile); Scanner keyboard = new Scanner(System.in); String primes[] = new String [1229]; String numSearch; int i = 0; while(input.hasNext()) { primes[i] = input.next(); i++; } System.out.println("Welcome!\n"); System.out.print("Enter a number from 1 to 10,000 or 'x' to exit: "); numSearch = keyboard.next(); while(!numSearch.equals("x")) { int location = binarySearch(primes, numSearch); if (location == -1) { System.out.println(numSearch + " is composite.\n"); } else { System.out.println(numSearch + " is prime!\n"); } System.out.print("Enter a number from 1 to 10,000 or 'x' to exit: "); numSearch = keyboard.next(); } System.out.println("Goodbye!"); input.close(); keyboard.close(); } private static int binarySearch(String[] arr, String key) { int low = 0; int high = arr.length; while (low <= high) { int mid = (low + high) / 2; if (arr[mid].equals(key)) { return mid; } else if (key.compareTo(arr[mid]) < 0) { high = mid - 1; } else { low = mid + 1; } } return -1; } }