Scanner工具类(流程控制的基础)在当前阶段,java中,可以进行人机交互的一个前提就是Scanner工具。 Scanner scanner = new Scanner(System.in); 我们使用Scanner的话需要用next()或者nextline()进行接收用户的数据。 例如:让我们去接收一个文字 public class Demo {public static void main(String[] args) {//此处为:设置一个扫描对象,用于接收键盘上传来的数据 Scanner scanner = new Scanner(System.in); System.out.println("请输入:"); if(scanner.hasNext()){//当键盘上的数据传来时,我们用nextline方法来接收 String st = scanner.nextLine(); //接收方式根据所选择数据结构的不同,也大为不同,例如:Int数据结构需要用nextInt来接收 System.out.println("输出内容:" st); } scanner.close(); } } 以这样的方式,我们在运行窗口上看到的就是交互式操作。 选择结构IF选择结构根据用途的不同,IF选择结构也会有单选、双选、多选、嵌套等方式。 语法为: if(布尔表达式){ //前提:是以布尔型表达式为true的情况*** } 由于if过于简单,此处我们只提一下多选择的情况 例如:某班级需要对同学们的成绩进行分级,而让学生在查成绩的时候可以明确查出自己考了哪一等级(此处的等级分为六个等级) public class IfDemo03 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in); /*明确一下:&&指的是“且”,当且仅当左右两方均正确才可进行{}里面的内容, 如果左边为错误,则其右边无法参与运算。 */ System.out.println("请输入成绩:"); int i = scanner.nextInt(); if(i<=100 && i>90){System.out.println("NB啊,太强了!"); }else if (i<=90 && i>80){System.out.println("不错不错有待加强!"); }else if (i<=80 && i>70){System.out.println("还行吧,慢慢来!"); }else if (i<=70 && i>60){System.out.println("唉,没事,及格了。"); }else if (i<=60 && i>0){System.out.println("怎么废啊,连及格都没成!"); }else if (i == 0){System.out.println("你想干啥?不想活了是吧!!!"); }else{System.out.println("咱们瞎蒙也得有个数吧!!!"); } scanner.close(); } } Switch选择结构Switch循环结构实行的有switch case语句 char grade = 'A'; switch (grade){case 'A': System.out.println("优秀"); break; default: System.out.println("不存在"); } case代表着穿透,而break代表的是终止,如果switch中case接收到了A,且后面没有break语句,则会把后面所有的内容全部读取出来。 从JDK 7之后switch循环结构支持字符串类型 循环结构循环结构分为三种:分别为while , do…while , for while循环结构while循环结构的语法表达式有点类似if, while(布尔表达式){ //循环内容 }
一个例子来介绍while循环结构:输出1~100 public class WhileDemo01 {public static void main(String[] args) {//输出1~100 int i = 0;//赋一个为零的整数变量 while (i<100){//不满足条件就会一直进行下去 i ; System.out.println(i);//输出语句放在了while循环里面 } } } do while循环语句do while循环语句和while循环语句的区别在于
举一个简单的例子: public class DoWhileDemo02 {public static void main(String[] args) {int a = 0; while (a<0){a ; System.out.println(a); } System.out.println("--------------");//此处为分界线 do {a ; System.out.println(a); }while (a<0); } /*同样都为在a<0的情况下输出a,此时的while循环已经不满足a<0,所以输出为“--------------” 而do while则先进了a ,所以输出结果为1。 */ } for循环 ******for循环是支持迭代的一种通用结构,是最有效、最灵活的循环结构 for(初始化;布尔表达式;更新){ //代码 } 先举一个简单的例子来表示for循环: public class ForDemo{ public static void main(String[] args){ int oddsum = 0;//定义奇数和 int evensum = 0;//定义偶数和 for(int i = 0;i <= 100;i ){//可以简化方式写100.for if(i % 2 != 0){//此处代表100除以2的余数不等于0 oddsum = i; }else evensum =i; } } System.out.println("偶数之和:" evensum); System.out.println("奇数之和:" oddsum); }来源:https://www./content-1-866451.html |
|