流程控制

1.Scanner


  1. next():以空白为结束符
    ​Scanner scanner = new Scanner(System.in); System.out.print("使用next()输入:");//hello world if (scanner.hasNext()) { String str = scanner.next(); System.out.println("输入的是:" + str);//hello } scanner.close(); ​
  2. nextLine():以​​Enter​​为结束符
    ​Scanner scanner = new Scanner(System.in); System.out.print("使用nextLine()输入:");//hello world if (scanner.hasNextLine()) { String str = scanner.nextLine(); System.out.println("输入的是:" + str);//hello world } scanner.close(); ​
  3. 例题:输入多个数字,求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输入出执行结果
    ​Scanner scanner = new Scanner(System.in); System.out.print("请输入:"); double sum = 0; int count = 0; while(scanner.hasNextDouble()) { double data = scanner.nextDouble(); System.out.println("你输入的是:" + data); sum += data; System.out.println("当前的和是:" + sum); ++count; System.out.println("当前是第" + count + "个数据"); } System.out.println("一共输入了" + count + "个数据"); System.out.println("总和是:" + sum); System.out.println("平均数是:" + sum /count); scanner.close(); ​