首页 > 编程语言 >Java: Switch

Java: Switch

时间:2022-11-24 03:44:06浏览次数:36  
标签:case Java System break Switch println day out

Instead of writing many if..else statements, you can use the switch statement.

int day = 4;
switch (day) { // every case will be a posibility of "day"
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}
// Outputs "Thursday" (day 4)

 

int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"

Without "break"

int day = 6;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
  case 7:
    System.out.println("Today is Sunday");
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs 
"Today is Saturday"
"Today is Sunday"
"Looking forward to the Weekend"

 

标签:case,Java,System,break,Switch,println,day,out
From: https://www.cnblogs.com/ShengLiu/p/16920699.html

相关文章

  • Java: Strings
    StringMethods:Stringtxt="HelloWorld";System.out.println(txt.toUpperCase());//Outputs"HELLOWORLD"System.out.println(txt.toLowerCase());//Outp......
  • Java: Type Casting
    InJava,therearetwotypesofcasting:WideningCasting (automatically)-convertingasmallertypetoalargertypesizebyte -> short -> char -> int......
  • Java: Primitive and Non-Primitive Data Types
    Primitivetypesarepredefined(alreadydefined)inJava.Non-primitivetypesarecreatedbytheprogrammerandisnotdefinedbyJava(exceptfor String).N......
  • Java: Declare Multiple Variables
    ExampleInsteadofwriting:intx=5;inty=6;intz=50;System.out.println(x+y+z);Youcansimplywrite:intx=5,y=6,z=50;System.out.printl......
  • IDEA报错 java: 错误: 无效的源发行版:17
    报错如下图所示:这就是没设置好JDK版本,按照下图设置好即可。好的,齐活儿。......
  • 一次对Java异常机制的理解
    一次对Java异常机制的理解近期有一个对接三方接口的任务,在这个过程中用到了许多try-catch处理,发现自己对异常处理是一知半解,浅浅研究了一下,记录一下,也帮助小伙伴如何正......
  • JavaScript 面向对象(五)原型链
     5.原型链prototype原型'每一个构造函数都有一个属性叫做prototype,指向一个对象,'当这个构造函数被new的时候,它的每一个实例(即将生成的对象)的__proto__属性,也指向......
  • JavaScript 面向对象(番外)JS字面量
    javascript字面量在JavaScript里面,字面量包括:字符串字面量(stringliteral)、数组字面量(arrayliteral)和对象字面量(objectliteral),另外还有函数字面量(function......
  • JavaScript 面向对象(一)对象
    字面量’字面量表示如何表达这个值,一般除去表达式,给变量赋值时,等号右边都可以认为是字面量。字面量分为字符串字面量(stringliteral)、数组字面量(arrayliteral)和对......
  • JavaScript--href调用JS方法和href="#"与href="javascript:void(0)"
    关于href属性<a>标签的href属性用于指定超链接目标的URL。超链接的URL可能的值:绝对URL-指向另一个站点(比如href="http://www.example.com/index.htm")相......