Jump to content

How to avoid repetition here

- - - - -

  • Please log in to reply
4 replies to this topic

#1
abderrahim

abderrahim

    Newbie

  • Members
  • PipPip
  • 14 posts
  • Programming Language:C, Java, PHP, Perl, Pascal, Assembly, Haskell
  • Learning:C, Java, PHP, JavaScript, PL/SQL, Assembly, Haskell
Hi everybody,
Is there a solution to avoid those ORs
char c;

c='a';

if (c=='a') || (c=='z') || (c=='r') {System.out.println(c);}

 
I used to do it in pascal like
if c in ['a','z','r'] then


#2
TheCompBoy

TheCompBoy

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 272 posts
You could maybe use a switch statement:

switch(c)

{

    case a:

             System.out.println(c);

             break;

    case z:

             System.out.println(c);

             break;

    case r:

             System.out.println(c);

             break;

}

Think my post we're usefull? Please take your time and press the Like button at my post, Big Thanks!
For great C# & Android tutorials visit my blogg: http://www.thecompboy.com/

#3
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
TheCompBoy, that's even more repetitive.

In case you have lot of chars you can use this:

        char c = 'z';        
        Character[] chars = new Character[]{'a','z','r'};
        HashSet<Character> set = new HashSet<Character>(Arrays.asList(chars));
        if(set.contains(c)){
            System.out.println("Set contains: "+c);            
        } else System.out.println("Set doesn't contain: "+c);
        


.

#4
abderrahim

abderrahim

    Newbie

  • Members
  • PipPip
  • 14 posts
  • Programming Language:C, Java, PHP, Perl, Pascal, Assembly, Haskell
  • Learning:C, Java, PHP, JavaScript, PL/SQL, Assembly, Haskell
Thank you very much,
since the switch statement has no place for an instruction that runs in all conditions(as I know!), we must put System.out.println each time, is there a solution to avoid repitition??

#5
bigneo

bigneo

    Newbie

  • Members
  • Pip
  • 4 posts
can you not use shared cases in switch method like this?

switch (c)

{

   case a:

   case z:

   case r: System.out.print("\nc");

}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users