当我们的程序需要获取用户输入的程序时,我们就需要用到Scanner类。Scanner类时Java5的新特征,主要用方法next()、nextLine()、nextInt()、nextFloat、nextDouble()。
- next():获取单个字符串,只有读到有效字符才能结束输入,不能得到有空格的字符串。
package Com.text;
import java.util.Scanner;
public class Scan {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = new String();
System.out.println("next输入字符串");
if(sc.hasNext()) {
str = sc.next();
}
System.out.println("输入的字符为:" + str);
sc.close();
}
}
2. nextLine():获取多个字符串,读取回车之前的字符串、即一行字符串;也可获取空格。
Scanner sc = new Scanner(System.in);
String str = new String();
System.out.println("nextLine获取输入字符串");
if(sc.hasNextLine()) {
str = sc.nextLine();
}
System.out.println("输入的字符为:" + str);
sc.close();
3. nextInt():获取Int型的整数值。
Scanner sc = new Scanner(System.in);
int[] a = new int[3];
System.out.println("输入整数:");
for(int i=0;i<3;i++){
a[i] = sc.nextInt();
}
System.out.println();
for(int i=0;i<3;i++){
System.out.print(a[i]+"\t");
}
sc.close();
4. nextFloat():获取Float型的浮点型数据。
Scanner sc = new Scanner(System.in);
float[] b = new float[3];
System.out.println("输入float型数据:");
for(int i=0;i<3;i++){
b[i] = sc.nextFloat();
}
System.out.println();
for(int i=0;i<3;i++){
System.out.print(b[i]+"\t");
}
sc.close();
5. nextDouble():获取Double型的数据。
Scanner sc = new Scanner(System.in);
double[] c = new double[3];
System.out.println("输入double型数据:");
for(int i=0;i<3;i++){
c[i] = sc.nextDouble();
}
System.out.println();
for(int i=0;i<3;i++){
System.out.print(c[i]+"\t");
}
sc.close();
6. 在上面五个方法名字的前面加上has,例如:hasNext()、hasInt() ,可以用来判断是否有输入的数据。
例如:
if(sc.hasNext())
最后,sc.close() = System.in.close()属于IO流的类中的方法,用来关闭输入流。如果不关闭会一直占用资源。最好在不使用输入流时,使用close()方法关掉,一般放在程序的末端。