Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Print out all odd numbers in random set of numbers ?

Hey guys,

so I'm doing some assignments in the R programming language, and I think it's kinda similair to java so hoping to get help here.

Suppose you have a random set of numbers, say 's <- c(1,5,4,2)'
How would I print out all odd numbers the integer way?

I can do it using booleans, like this:
s[lapply(s, "%%", 2) != 0]

But how would I do it using integers?
Obviously, s[c(1,2)] wouldn't work because if the set of number changes, it doesn't hold anymore.

Help would be appreiciated!
in java:
int[] arr = new int[]{1,5,4,2};

for(int i=0; i<arr.length; i++){
System.out.print(arr[i] * (arr[i]%2));
}

you cant make decisions without using booleans so it will print 0 if the number was even.
not really sure if that is what you wanted but it will print all odd numbers and will print 0 if the number was even
you would have to use a boolean to filter out the even numbers completely.
https://stackoverflow.com/questions/1895...egers-in-r
[Image: CJLOhGd.gif]
Code
public class oddInt
{
    public static void main(String[] args)
     {
          int[] array = new int[]{5,2,4,6,1,3, 9, 7 ,3, 23,43,1,2,34,5,6,7,10};
          for(int i = 0; i < array.length; i++)
          {
               if(array[i] % 2 != 0)
               {
                    System.out.println(array[i]);
               }
      }
}

}


Output:
5
1
3
9
7
3
23
43
1
5
7
[Image: wF9v28t.gif]
(Feb 6, 2019 08:27 PM)Talon Wrote:  
Code
public class oddInt
{
    public static void main(String[] args)
    {
         int[] array = new int[]{5,2,4,6,1,3, 9, 7 ,3, 23,43,1,2,34,5,6,7,10};
         for(int i = 0; i < array.length; i++)
         {
              if(array[i] % 2 != 0)
              {
                   System.out.println(array[i]);
              }
     }
}

}


Output:
5
1
3
9
7
3
23
43
1
5
7

You can also use this since Java 8:
Code
public class OddInt {
   public static void main(String[] args) {
       int[] array = {5, 2, 4, 6, 1, 3, 9, 7, 3, 23, 43, 1, 2, 34, 5, 6, 7, 10};
       Arrays.stream(array).filter(x -> (x % 2 != 0)).forEach(System.out::println);
   }
}

Looks more sexy to me to do it in a functional style, and streaming can also boost performance


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by ShallowMEFeb 17, 2020 07:08 PM 20 517 Feb 17, 2020 07:08 PM
Last Post: 0xDEAD10CC
[Java] by Nemo2478Aug 25, 2019 05:12 PM 8 482 Aug 25, 2019 05:12 PM
Last Post: Nemo2478
[Java] by cryptobassboostMay 20, 2019 11:49 AM 4 248 May 20, 2019 11:49 AM
Last Post: bluriy