I'm trying to solve this question, but the NumberFormatException always happens. Using try-catch doesn't give me what I want because it always results in printing out "invalid input!" Please help me.
The following is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class BTECtry2 {
public static int binarySearch(double[] arr2, int L, int R, double x) {
if (L <= R) {
int mid = L + (R - L) / 2;
if (arr2[mid] == x) {
return mid;
}
if (arr2[mid] > x) {
return binarySearch(arr2, L, mid - 1, x);
} else {
return binarySearch(arr2, mid + 1, R, x);
}
}
return -1;
}
public static void insertionSort(double[] arr) {
int x = arr.length;
for (int i = 0; i < x; i++) {
int y = i;
Double money;
for (int j = i; j < x; j++) {
if (arr[j] < arr[y]) {
y = j;
}
}
if (y != i) {
money = arr[y];
arr[y] = arr[i];
arr[i] = money;
}
}
}
public static void main(String[] args) throws IOException {
int[] USDcoin = new int[15];
double[] JDcoin = new double[15]; // size is 15 for both arrays because there are 15 values in the txt file
String coins = "USD.txt";
BufferedReader reader = new BufferedReader(new FileReader(coins));
String y;
int i = 0;
while ((y = reader.readLine()) != null) {
int temp = Integer.parseInt(y);
USDcoin[i] = temp;
JDcoin[i] = temp * (0.71);
i += 1;
}
while (true) {
System.out.println("P. to display the array");
System.out.println("D. to sort the array");
System.out.println("S. search for a number in array");
System.out.println("Q. Quit the program");
System.out.print("Enter your choice from the list above: ");
Scanner input = new Scanner(System.in);
String list;
list = input.next();
switch (list) {
case "P" -> {
for (int j = 0; j < JDcoin.length; j++) {
System.out.println(JDcoin[j]);
}
}
case "D" -> {
insertionSort(JDcoin);
for (int j = 0; j < JDcoin.length; j++) {
System.out.println(JDcoin[j]);
}
}
case "S" -> {
Double value;
System.out.println(" Enter number : ");
value = input.nextDouble();
int w = binarySearch(JDcoin, 0, JDcoin.length, value);
if (w == -1) {
System.out.println(" Coin searched for is not found! ");
} else {
System.out.println(" Coin searched for is found! ");
}
}
case "Q" -> {
reader.close();
System.exit(0);
}
default -> {
System.out.println(" Invalid input! ");
}
}
}
}
}
The "USD.txt" file is just a txt file with a random list of number as follows:
200
100
400
350
800
750
250
200