I am suppose to find odd numbers in an integer for HW. So countOddigtis(56781) should return( NOT PRINT ) 5 7 1. My approach was to convert the integer into a string and use that to return. Problems I am having are
Missing return statement error, even though I have a return statement in the if statement. Can someone explain what this error means and how to get past it?
It prints the wrong answer 49 for 56781 when I put return x; at the end of the method.
Can Java solve stringn.charAt(x) % 2 != 0 considering I am might(NOT SURE) be comparing a string or char with an int?
PS keep it simple, I don't much Java, I just started.
int countOddigits( int n )
{
int x = 0;
String stringn = Integer.toString(n);
while ( x <= stringn.length() - 1 )
{
if ( stringn.charAt(x) % 2 != 0 )
{
return stringn.charAt(x);
}
x++;
}
}
public void run()
{
System.out.printf("Odd number is %d\n: ", countOddigits(567981) );
}
You presumably don't want to return immediately when you find the first odd digit. You also need to convert the result back into an int
(to match your return type). You can parse
it with Integer.parseInt(String)
; and you can build that String
with a StringBuilder
. Also, you could make the method static
. Like,
static int countOddDigits(int i) { // <-- camel case, that is camelCase
StringBuilder sb = new StringBuilder();
// for each char ch in the String form of i converted to a character array
for (char ch : String.valueOf(i).toCharArray()) {
if (Character.digit(ch, 10) % 2 != 0) {
sb.append(ch);
}
}
return Integer.parseInt(sb.toString());
}
Then, to test it, you can call it like
public static void main(String[] args) {
int oddDigits = countOddDigits(56781);
System.out.println(oddDigits);
}
Which outputs
571
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.