logo

Virkne Switch paziņojumā

Programmā Java 7 Java ļauj izmantot virknes objektus slēdža priekšraksta izteiksmē. Lai izmantotu virkni, jums jāņem vērā šādi punkti:

  • Tam jābūt tikai virknes objektam.
  •  Object game = 'Hockey'; // It is not allowed String game = 'Hockey'; // It is OK. 
  • Virknes objekts ir reģistrjutīgs.
  •  'Hickey' and 'hocker' are not equal. 
  • Nav Null objekta

esiet piesardzīgs, nododot virknes objektu, nododot nulles objekta cēloni NullPointerException.


Virkne Switch paziņojumā 1. piemērs

 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'); } } } 

Izvade:

 Let's play Cricket 

Virkne Switch paziņojumā 2. piemērā

 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?'); } } } 

Izvade:

 This is a indoor game