Question: I am trying to write a function that will take in a string with numbers and return true if there are more even numbers than
I am trying to write a function that will take in a string with numbers and return true if there are more even numbers than odd numbers and return false if there are more odd numbers.
Here is my code:
public static Boolean hasMoreEvenThanOdd(String sentence) {
int evenCount=0;
int oddCount=0;
int num;
int x=Integer.parseInt(sentence);
while(x>0) {
num=x%10;
if(num%2==0) {
evenCount++;
}else if(num%2==1) {
oddCount++;
}
x/=10;
}
return evenCount>oddCount;
}
The errors I am getting are:
Exception in thread "main" java.lang.NumberFormatException: For input string: "7 8 9 -10 11 4 6 88"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at a3.LoopsAndImages.hasMoreEvenThanOdd(LoopsAndImages.java:44)
at a3.LoopsAndImages.main(LoopsAndImages.java:10)
I am testing it with this in my main:
Boolean numbers = hasMoreEvenThanOdd("7 8 9 -10 11 4 6 88");
System.out.println(numbers);
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
