Scanner对象

1. Scanner对象用来接收键盘输入,常用的方法有:

next()
nextLine()
hasNext()
close()

package com.langtao.scanner;

import java.util.Scanner;

public class Demo1 {
public static void main(String[] args) {
//新建scanner对象,用来接收键盘的输入
Scanner scanner = new Scanner(System.in);

System.out.println("Please input something: ");
//hasNext()用来判断是否有键盘输入
if(scanner.hasNext()){
String str = scanner.nextLine();
System.out.println("The commands you entered is: "+str);
}

//请注意,使用完Scanner对象以后,调用close()释放资源
scanner.close();
}
}

2.Scanner对象的其他常用方法:

hasNextInt()
hasNextFloat()

package com.langtao.scanner;

import java.util.Scanner;
public class Demo3 {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double sum = 0;
int m = 0;
System.out.println("Please enter the first number: ");
while(scanner.hasNextDouble()){
sum = sum + scanner.nextDouble();
m++;
System.out.println("There are "+m+" numbers, and the sum is :"+sum+" , so the average is :"+ sum/m);
System.out.println("Please enter the number: ");
}
}
}

posted @ 2020-11-08 22:36  浪淘  阅读(168)  评论(0)    收藏  举报