Question

How can I get all the odds number on the users input. Example: input : "avhguhrgr18543" the output should be "153" but in my code it gives up to 9... I really need the code that only get the odd number base on the users input.

String s;
System.out.println("Input anything you want: ");
Scanner scanner = new Scanner(System.in);
s = scanner.nextLine();

int n = 10;
System.out.println("Odd Numbers are");
for(int i=1;i<=n;i++) {
  if(i%2!=0) {
    System.out.print(i + " ");
  }
}

No correct solution

OTHER TIPS

Try,

String s = "avhguhrgr18543";
for (int i = 0; i < s.length(); i++) {
  char ch = s.charAt(i);
  if (Character.isDigit(ch) && (ch & 1) == 1) {
                                    // Use bitwise & for performance
       System.out.print(ch);
    }
 }

Try the below code,

    String s; 
    System.out.println("Input anything you want: "); 
    Scanner scanner = new Scanner(System.in);
    s = scanner.nextLine();

    //int n = 10;
    System.out.println("Odd Numbers are"); 

    for(int i=0;i<s.length();i++) 
    { 
        char ch = s.charAt(i);
        if(Character.isDigit(ch)  &&  (ch % 2) !=0) 
        { 
            System.out.print(ch + " "); 
        } 
    } 

OUTPUT

Input anything you want:
123456
Odd Numbers are 1 3 5

You're not iterating the input characters, you're iterating the numbers between 1 and 10.

What you have to do is :

for (int i = 0; i < s.length(); i++) {
    char next = s.charAt(i);
    if (Character.isDigit(next) && (next - '0') % 2 == 1) {
       System.out.print(next + " ");
    }
}

use isDigit() function

for(i=0;i<s.length();i++)
{
    if(s[i].isDigit())
         //Convert it to int and find if it is odd. Then print it
}

The best way will be to reuse Java's regex package with the modulo operator to identify only the odds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top