从键盘读取
import java.util.Scanner;
public class Demo {
public static void main(String[] args ) {
Scanner input = new Scanner(System.in);
System.out.println("请输出一个整数:");
int i = input.nextInt();
System.out.println("你输入的整数是:" + i);
}
}
从字符串读取
import java.util.Scanner;
public class Demo {
public static void main(String[] args ) {
//这里的\r\n是换行符,Linux下其实只用\n即可
Scanner input = new Scanner("hello\r\nworld\r\n");
//循环读取,hasNext()方法和集合框架里面的一样使
while(input.hasNext()) {
//每次读取一行,别的读取方法见API,比较简单
String s = input.nextLine();
System.out.println(s);
}
}
}
从文件读取
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Demo {
public static void main(String[] args ) {
String path = File.separator + "home" + File.separator + "siu" +
File.separator + "work" + File.separator + "demo.txt";
File f = new File(path);
Scanner input = null;
try {
//从文件构造Scanner对象,有可能产生异常
input = new Scanner(f);
while(input.hasNext()) {
String s = input.nextLine();
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
input.close();
}
}
}
image.png
网友评论