The target goal of my problem is to find the largest even number from an input of random text and numbers, always ending with a dot. E.g "Planets 35678 stars 76 travels 14555 or cookies. " ---> 35678
I have the following code, which works well with my ID, but elsewhere it gives java.lang.NumberFormatException. I did the best I could to strip the String off letters and the (.) Any ideas what's giving the exception?
Here is the code:
Scanner input = new Scanner(System.in);
String s = input.nextLine();
s = s.replaceAll("[a-zA-Z]", "");
s = s.replace(".", "");
String newString = s.trim();
String yourString = newString.replaceAll("\\s+", " ");
String[] array = yourString.split(" ");
int[] b = new int[array.length];
for (int i = 0; i < array.length; i++) {
b[i] = Integer.parseInt(array[i]);
}
int largest = Integer.MIN_VALUE;
for (int number : b) {
if (number % 2 == 1) {
continue;
}
if (number > largest) {
largest = number;
}
}
System.out.println(largest);
}
Aucun commentaire:
Enregistrer un commentaire