输入hello world,得到结果为hello,因为此方法读取到空格立马停止
nextLine() public class Demo02 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入信息:"); if(scanner.hasNextLine()){ String str = scanner.nextLine(); System.out.println("输入的信息为" + str); } scanner.close(); }}输入hello world,得到结果为hello world,此方法可以读取空格
小程序 可以输入多个数字,并求其总和和平均值,每输入一个数字用回车确认,通过输入非数字来终止并计算其结果 public class Demo03 { //可以输入多个数字,并求其总和和平均值,每输入一个数字用回车确认,通过输入非数字来终止并计算其结果 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //定义sum用来求和 double sum = 0; //定义count用来记录输入次数 int count = 0; //通过循环来判断是否还有输入,并再里面对数值进行计算 while (scanner.hasNextDouble()){ count ++; sum += scanner.nextDouble(); } System.out.println("您输入的和为:" + sum); System.out.println("您输入的平均值为:" + (sum/count)); scanner.close(); }}