logo

Niz v izjavi Switch

V Javi 7 vam Java omogoča uporabo nizovnih objektov v izrazu stavka switch. Če želite uporabiti niz, morate upoštevati naslednje točke:

  • To mora biti le objekt niza.
  •  Object game = 'Hockey'; // It is not allowed String game = 'Hockey'; // It is OK. 
  • Objekt niza razlikuje med velikimi in malimi črkami.
  •  'Hickey' and 'hocker' are not equal. 
  • Ni ničelnega predmeta

bodite previdni pri posredovanju objekta niza, pri čemer NullPointerException posredujete vzrok ničelnega objekta.


Niz v stavku Switch Primer 1

 public class StringInSwitchStatementExample { public static void main(String[] args) { String game = 'Cricket'; switch(game){ case 'Hockey': System.out.println('Let's play Hockey'); break; case 'Cricket': System.out.println('Let's play Cricket'); break; case 'Football': System.out.println('Let's play Football'); } } } 

Izhod:

 Let's play Cricket 

Niz v stavku Switch Primer 2

 public class StringInSwitchStatementExample { public static void main(String[] args) { String game = 'Card-Games'; switch(game){ case 'Hockey': case'Cricket': case'Football': System.out.println('This is a outdoor game'); break; case 'Chess': case'Card-Games': case'Puzzles': case'Indoor basketball': System.out.println('This is a indoor game'); break; default: System.out.println('What game it is?'); } } } 

Izhod:

 This is a indoor game