Java中Scanner用法

Scanner可以实现程序和人的交互,用户可以利用键盘进行输入。

不同类型的输入:

String s=sc.next(); //接受字符串数据

System.out.println(s);

int s1= sc.nextInt();//接受整型数据

System.out.println(s1);

double s2= sc.nextDouble();//接受小数数据

System.out.println(s2);

例如:从键盘输入hello world。

import java.util.Scanner; //先导入Java.util.Scanner包

public class test {

public static void main(String[] args) {

//创建一个扫描器对象,用于接收键盘数据

Scanner sc=new Scanner(System.in);

//从键盘接收数据

String s=sc.next(); //接受字符串数据

System.out.println(s);

}

}

hello world

hello

上述之所以只会输出“hello”,是因为这种输入遇到空格、制表符、回车就停止接受,因此,就不会接受“hello”后面的数据了。我们要想接受完整的“hello world”,可使用nextline()来接受。

nextline()是接受一行,可以接受空格、制表符,只有遇到回车才会停止接受数据。

import java.util.Scanner; //先导入Java.util.Scanner包

public class test {

public static void main(String[] args) {

//创建一个扫描器对象,用于接收键盘数据

Scanner sc=new Scanner(System.in);

//从键盘接收数据

String s= sc.nextLine(); //接受字符串数据

System.out.println(s);

}

}

hello world

hello world

参考文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: