Java获取用户的输入可以使用Scanner和流的方式,在这里我介绍两种方法
1.使用Scanner
-
import java.util.Scanner;
-
public class Test {
-
public static void main(String[] args) {
-
-
Scanner sc=new Scanner(System.in);
-
while(sc.hasNext())
-
{
-
System.out.println("输出:"+sc.next());
-
}
-
-
}
-
}
使用Scanner的方式获取用户的输入的话,Scanner默认使用空格,Tab,回车作为输入项的分隔符。
可以使用sc.useDelimiter()方法来改变这种默认。
sc可以读取特定的数据,比如int,long看下图

从图中可以看到nextBoolean,nextFloat等等。
Scanner提供一个简单的方法一行一行的读取
-
import java.util.Scanner;
-
public class Test {
-
public static void main(String[] args) {
-
-
Scanner sc=new Scanner(System.in);
-
-
while(sc.hasNextLine())
-
{
-
System.out.println("输出:"+sc.nextLine());
-
}
-
-
}
-
}
Scanner不仅可以读取用户键盘的输入,也可以读取文件
-
import java.io.File;
-
import java.util.Scanner;
-
-
public class Test {
-
public static void main(String[] args) throws Exception
-
{
-
-
Scanner sc=new Scanner(new File("C:\\Users\\zhycheng\\Desktop\\Dota超神\\描述.txt"));
-
-
while(sc.hasNextLine())
-
{
-
System.out.println("输出:"+sc.nextLine());
-
}
-
-
}
-
}
2.使用BufferedReader
需要指出的是Scanner是Java5提供的工具类,在Java5之前使用BufferedReader来读取
-
import java.io.BufferedReader;
-
import java.io.InputStreamReader;
-
-
public class Test {
-
public static void main(String[] args) throws Exception
-
{
-
-
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
-
String str=null;
-
while((str=br.readLine())!=null)
-
{
-
System.out.println(str);
-
}
-
-
}
-
}
版权声明:本文为博主http://www.zuiniusn.com原创文章,未经博主允许不得转载。
Java获取用户的输入
原文:http://blog.csdn.net/u013948191/article/details/46829011