用户交互Scanner

之前学习的基本语法中并没有实现程序和人的交互,Java提供了一个工具类,可以获取用户的输入。java.util.Scanner是Java5的新特征,可以通过Scanner类来获取用户的输入

  • 语法

    Scanner s = new Scanner(System.in)
    
  • 通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext() 与 hasNextLine() 判断是否还有输入的数据。

    public class Demo01 {
    
        public static void main(String[] args) {
    
            //创建一个扫描器对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
    
            System.out.println("使用next方法接收:");
    
            //判断用户是否输入字符串
            if (scanner.hasNext()){
                //使用next方式接收
                String str = scanner.next();
                System.out.println("输入的内容为:"+str);
            }
            //凡事属于IO流的类,如果不关会一直占用资源
            scanner.close();
        }
    }
    

    tips

    • next():

      1. 一定要读取到有效字符后才可以结束输入

      2. 对输入有效字符前遇到的空白,next() 方法会自动将其去掉

      3. 只有输入有效字符后,才将其后面输入的空白作为分隔符或结束符

      4. next() 不能得到带有空格的字符串

    • nextLine():

      1. 以 Enter 为结束符,也就是说 nextLine() 方法返回的是输入回车之前的所有字符

      2. 可以获得空白

  • 练习

    public class Demo03 {
        public static void main(String[] args) {
    
            Scanner scanner = new Scanner(System.in);
    
            //从键盘接收数据
            int i = 0;
            float f = 0.0f;
    
            System.out.println("请输入整数:");
    
            if (scanner.hasNextInt()){
                i = scanner.nextInt();
                System.out.println("整数数据:" + i);
            }else {
                System.out.println("输入的不是整数数据");
            }
    
            System.out.println("请输入小数:");
    
            if (scanner.hasNextFloat()){
                f = scanner.nextFloat();
                System.out.println("小数数据:" + f);
            }else {
                System.out.println("输入的不是小数数据");
            }
    
            scanner.close();
        }
    }
    
    public class Demo04 {
        public static void main(String[] args) {
            //我们可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果:
            Scanner scanner = new Scanner(System.in);
    
            //定义 和
            double sum = 0;
            //定义 数字个数
            int i = 0;
    
            System.out.println("请输入数据:");
            //通过循环判断是否还有输入,并在里面对每一次进行求和和统计
            while (scanner.hasNextDouble()){
                double x = scanner.nextDouble();
    
                i++;
                sum = sum + x;
    
                System.out.println("你输入了第"+i+"个数据,和为"+ sum  + ",平均值为"+ (sum/i));
            }
    
            System.out.println("输入的数字和为:" + sum);
            System.out.println("输入的平均值为:"+ (sum/i));
    
            scanner.close();
        }
    }
    

顺序结构

  • Java的基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行。他是任何一个算法都离不开的一种基本算法结构。

选择结构

if单选择结构

在需要判断一个东西是否可行,然后才去执行的过程,用if语句来表示

  • 语法

    If(布尔表达式){
    //如果布尔表达式为true将执行的语句
    }
    
    public class IfDemo01 {
        public static void main(String[] args) {
    
            Scanner scanner = new Scanner(System.in);
    
            System.out.println("请输入一个内容:");
            String str = scanner.nextLine();
    
            //equals 判断字符串是否相等
            if (str.equals("hello")){
                System.out.println(str);
            }
            System.out.println("End");
            scanner.close();
        }
    }
    

if双选择结构

例:公司收购一个软件,成功了,给别人支付100万元,失败了自己找人开发。

对于这个问题一个if无法解决,需要有两个判断,需要一个双选择结构,所以有了if-else结构。

  • 语法

    if(布尔表达式){
      //如果布尔表达式为true
    }else{
      //如果布尔表达式为false
    }
    
    public class IfDemo02 {
        public static void main(String[] args) {
    
            //考试分数大于等于60分就是及格,小于60分就是不及格
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入成绩:");
            int score = scanner.nextInt();
    
            if (score >= 60) {
                System.out.println("及格");
            } else {
                System.out.println("不及格");
            }
            scanner.close();
        }
    }
    

if多选择结构

在实际情况中,可能存在ABCD,存在区间多级判断,比如90-100为A,80-90为B,60-80为C,小于60为D。

  • 语法

    if(布尔表达式1){
      //如果布尔表达式1的值为true执行代码
    }else if(布尔表达式2){
      //如果布尔表达式2的值为true执行代码
    }else if(布尔表达式3){
      //如果布尔表达式3的值为true执行代码
    }else{
      //如果以上布尔表达式都不为true执行代码
    }
    
    public class IfDemo03 {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.println("请输入成绩:");
            /*
            if 语句至多有1个 else 语句,else 语句在所有的 else if 语句之后。
            语句可以有若干个 eLse if 语句,它们必须在 else 语句之前。
            一旦其中一个 else tf 语句检测为 true,其他的 else if 以及else 语句都将跳过执行。
            */
            int score = scanner.nextInt();
    
            if (score >= 90 && score <= 100){
                System.out.println("您的成绩为A");
            }else if (score >= 80 && score < 90){
                System.out.println("您的成绩为B");
            }else if (score >= 60 && score < 80){
                System.out.println("您的成绩为C");
            }else if (score >= 0 && score < 60){
                System.out.println("您的成绩为D");
            }else {
                System.out.println("请输入正确的成绩");
            }
            scanner.close();
        }
    }
    

嵌套的if结构

使用嵌套的 if…else 语句是合法的。也就是说,可以在另一个 if 或者 else if 语句中使用 if 或 else if 语句。

  • 语法

    if(布尔表达式1){
      //如果布尔表达式1的值为true执行代码
      if(布尔表达式2){
        //如果布尔表达式2的值为true执行代码
      }
    }
    

switch多选择结构

多选择结构还一个实现方式为 switch case 语句。

switch case 语句判断一个变量与一系列值是否相等,每个值称为一个分支。

  • 语法

    switch(expression){
      case value :
        //语句
        break;//可选
      case value :
        //语句
        break;//可选
      //可以有任意数量的case语句
      default ://可选
        //语句
    }
    
  • switch 语句中的变量类型可以是:

    1. byte、short、int或者char

    2. Java SE 7 开始,switch支持字符串String类型

    3. 同时 case 标签必须为字符串常量或字面量

    public class SwitchDemo01 {
        public static void main(String[] args) {
            //switch 匹配一个具体的值 //case 穿透
    
            char grade = 'C';
    
            switch (grade){
                case 'A':
                    System.out.println("优秀");
                    break;//不结束就会一直向下执行,输出全部
                case 'B':
                    System.out.println("良好");
                    break;
                case 'C':
                    System.out.println("一般");//没有 break 会穿透
                case 'D':
                    System.out.println("及格");
                    break;
                case 'E':
                    System.out.println("不及格");
                    break;
                default:
                    System.out.println("错误");
            }
        }
    }
    
    public class SwitchDemo02 {
        public static void main(String[] args) {
            String name = "BruisesL";
            //JDK7 新特性,表达式结果可以是字符串
            //字符的本质还是数字
            switch (name){
                case "BruisesL":
                    System.out.println("oooooooops");
                    break;
                case "lxc":
                    System.out.println("noop");
                    break;
                default:
                    System.out.println("emmmmm");
            }
    
        }
    }
    

循环结构

  • while 循环

    while(布尔表达式){
      //循环内容
    }
    
    1. 只要布尔表达式为true,循环就会一直进行下去。

    2. 一般会让循环停下来,需要一个让表达式失效的方式来结束循环。

    3. 少部分情况需要循环一直执行,比如服务器的请求响应监听等。

    4. 循环条件一直为true就会造成无限循环【死循环】,正常的业务编程中应该尽量避免死循环,会影响程序性能或者导致程序卡死崩溃。

    public class WhileDemo01 {
        public static void main(String[] args) {
    
            //输出1-100
            int i = 0;
    
            while (i<100){
                i++;
                System.out.println(i);
            }
        }
    }
    
    public class WhileDemo01 {
        public static void main(String[] args) {
    
            //输出1-100
            int i = 0;
    
            while (i<100){
                i++;
                System.out.println(i);
            }
        }
    }
    
    public class WhileDemo02 {
        public static void main(String[] args) {
    
            //计算1+2+3+...+100的值
            int i = 0;
            int sum = 0;
    
            while (i<100){
                i++;
                sum = sum + i;
            }
            System.out.println(sum);
        }
    }
    
  • do…while 循环

    对于 while 语句,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。

    do…while 循环和 while 循环相似,不同的是 do…while 循环至少会执行一次。

    do{
      //代码语句
    }while(布尔表达式);
    
    • tips

      while 和 do…while 的区别:

      1. while 先判断后执行,do…while 先执行后判断

      2. do…while 总是保证循环体会被至少执行一次

    public class DoWhileDemo01 {
        public static void main(String[] args) {
             int i = 0;
             int sum = 0;
    
             do {
                 i++;
                 sum = sum + i;
             }while (i<100);
            System.out.println(sum);
        }
    }
    
    public class DoWhileDemo02 {
        public static void main(String[] args) {
            int a = 0;
    
            while (a<0){
                System.out.println(a);
                a++;
            }
            System.out.println("=======================");
    
            do {
                System.out.println(a);
                a++;
            }while (a<0);
        }
    }
    
  • for 循环

    虽然所有循环结构都可以用 while 或者 do…while 表示,但 Java 提供了另一种语句——for 循环,使一些循环结构变得更加简单。

    1. for 循环语句是支持迭代的一种通用结构,是最有效的、最灵活的循环结构。

    2. for 循环执行的次数是在执行前就确定的

    语法:

    for(初始值;布尔表达式;更新){
      //代码语句
    }
    
    public class ForDemo01 {
        public static void main(String[] args) {
            int a = 1;//初始化条件
    
            while (a <= 10){//条件判断
                System.out.println(a);//循环体
                a+=2;//迭代
            }
            System.out.println("while循环结束");
    
            for (int i = 1;i <= 10;i+=2){
                System.out.println(i);
            }
            System.out.println("for循环结束");
            /*
            关于 for 循环有以下几点说阴:
            最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。例如提前定义int i = 1;for(;i < 10;i++)
            然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
            执行一次循环后,更新循环控制变量(迭代因子控制循环变量的增减)。
            再次检测布尔表达式。循环执行上面的过程。
             */
        }
    }
    
    public class ForDemo02 {
        public static void main(String[] args) {
            //练习1:计算0到100之间的奇数和偶数的和
    
            int oddsum = 0;
            int evensum = 0;
    
            for (int i = 0; i < 101; i++) {
                if (i % 2 != 0){
                    oddsum += i;
                }else {
                    evensum += i;
                }
            }
            System.out.println("奇数和为:" + oddsum + "\n" + "偶数和为:" + evensum);
        }
    }
    
    public class ForDemo03 {
        public static void main(String[] args) {
            //练习2:用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
    
            for (int i = 1; i <= 1000; i++) {
                if (i % 5 == 0){
                    System.out.print(i+"\t");//print 输出完不会换行
                }
                if (i % (5*3) == 0){
                    System.out.println();
                    //println 输出完会换行
                }
            }
        }
    }
    
    public class ForDemo04 {
        public static void main(String[] args) {
            //练习3:打印99乘法表
            for (int i = 1; i < 10; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(i + "*" + j + "=" +(i*j) + "\t");
                    /*
                    if (i == j){
                        System.out.println();
                    }
                    由于第二次循环最后一次true的条件就是 i == j,因此与 在第一次循环加换行 即可
                     */
                }
                System.out.println();
            }
        }
    }
    
    • 增强 for 循环
    for(声明语句 : 表达式)
    {
      //代码句子
    }
    

    声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循 环语句块,其值与此时数组元素的值相等。

    表达式:表达式是要访问的数组名,或者是返回值为数组的方法。

    public class ForDemo05 {
        public static void main(String[] args) {
            int[] numbers = {10,20,30,40,50}; //定义一个数组
    
            for (int i = 0; i < 5; i++) {
                System.out.println(numbers[i]); //输出数组 number 中的第 i 个数
            }
            System.out.println("==========================");
            //遍历数组的元素
            for (int x:numbers) {
                System.out.println(x);
            }
        }
    }
    

break & continue

  • break在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)

  • continue 语句用在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。

    public class BreakDemo01 {
        public static void main(String[] args) {
            int i = 0;
            while (i < 100){
                i++;
                System.out.println(i);
                if (i == 30){
                    break;
                }
            }
        }
    }
    
    public class ContinueDemo01 {
        public static void main(String[] args) {
            int i =0;
            while (i < 100){
                i++;
                if (i % 10 == 0){
                    System.out.println();
                    continue;
                }
                System.out.print(i + " ");
            }
        }
    }
    
    public class ReturnDemo01 {
    	public static void main(String[] args) {
    		for (int j = 1; j <= 10; j++) {
    			for (int i = 1; i <= 10; i++) {
    				System.out.print(i + "\t");
    				return;
    				System.out.println();
    			}
    		}	
    	}
    }
    
  • 关于 goto 关键字

    1. goto 关键字很早就在程序设计语言中出现。尽管 goto 仍是 Java 的一个保留字,但并未在语言中得到正式使用;Java 没有 goto。然而,在 break 和 continue 这两个关键字的身上,我们仍然能看出一些 goto 的影子—-带标签的 break 和 continue 。

    2. “标签〞是指后面跟一个冒号的标识符,冒号前可以是任意非关键字的词,例如:label:

    3. 对 Java 来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另一个循环,由于 break 和 continue 关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。

    public class LabelDemo01 {
        public static void main(String[] args) {
            //打印101-150之间所有的质数
             int count = 0;
    
            outer:for (int i = 101; i < 150; i++) {
                for (int j = 2; j < i/2; j++) {
                    if (i % j == 0){
                        continue outer;
                    }
                }
                System.out.print(i + " ");
            }
        }
    }
    

练习

public class TestDemo01 {
    public static void main(String[] args) {
        //打印三角形 5行

        for (int i = 1; i <= 5; i++) {
            for (int j = 4; j >= i ; j--) {
                System.out.print(" "); //打印左上角倒三角,用空格占位
            }
            for (int j = 1; j <= (i * 2 - 1); j++) {
                System.out.print("*");
            }
            /* 如果第二次循环打印与左上互补的直角三角形,即
            for (int j = 1; j <= i; j++){
                System.out.print("*");
            }
            则需要补全右半直角三角形
            for (int j = 1; j < i; j++) {
                System.out.print("*");
            }
             */
            System.out.println();
        }
    }
}