I am fairly new to Java programming, thus facing issues to handle issues such as this. I am writing a program to check if the string input contains at least 2 odd numbers. As part of the problem which I am solving, it asks me to take input for the number of digits my number will have - but that is irrelevant at this point.
I have attempted to traverse through the string and record the first two found odd numbers in a string and then print it. But it seems to fail and I can't understand why.
NB: If the string input is 12272
, then it should print 17
as these two are the only odd numbers.
package myPackage;
import java.util.Scanner;
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int tc = scanner.nextInt();
while(true){
String str="";
int n = scanner.nextInt();
String num = scanner.nextLine();
int cnt = 0;
for (int i = 0; i < num.length(); i++) {
int extractedDigit = Integer.parseInt(Character.toString(num.charAt(i)));
if(extractedDigit % 2 != 0){
cnt++;
str += Integer.toString(extractedDigit);
if(cnt == 2)break;
}
}
if(cnt == 2) System.out.println(str);
else System.out.println("-1");
if(tc == 0)break;
tc--;
}
}
}