标准输入和格式化输出
这里主要是从键盘和文件读入数据,将数据格式化输出到控制台或者文件。灵活使用,会用即可;用时需要随用随查;
java.util.Scanner提供了标准输入,比较有用的方法有
Scanner(InputStream input) :初始化一个Scanner实例
String nextLine() : 读入一行,不论是否有空格
String hasNext() :是否还有字符串
String next() :以空格作为分隔符
String hasNextInt()
String nextInt() :读入一个整数
String hasNextDouble()
String nextDouble():读入一个double
标准输入:new Scanner(System.in)
从文件输入:new Scanner(new File(filename))
格式化输出到控制台:System.out.printf(fmt, object...)
格式化输出到文件:PrintWriter(new File(filename))
printer.printf(fmt, object...)
printer.close()
package supermarket;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.File;
/**
* Created by wzl.
*/
public class InputOfOutput {
public void testInputOfOutput() throws FileNotFoundException{
/*
从文件格式化输入
*/
Scanner ittn = new Scanner(new File("C:/hello.txt")); // 将参数改为System.in可以从键盘输入
// Scanner ittn = new Scanner(System.in);
// System.out.println("请输入值:");//参数改为输入值后,while一直循环,需要小解决下
// 文件内容:ssssssss 123 31313.111
while(ittn.hasNext()){
// System.out.println(ittn.next()); // ssssssss
// System.out.println(ittn.nextInt()); // 123
// System.out.println(ittn.nextDouble()); //31313.111
System.out.print(ittn.nextLine());
// System.out.println(ittn.hasNextLine());
// System.out.println(ittn.hasNext());
System.out.println(ittn.hasNextInt());
}
/*
格式化输出到控制台
*/
// int data = 1234;
// double hello = -1234.13214134;
// System.out.printf("整数是%d\n", data); // 1234
// System.out.printf("浮点数是%7.3f\n", hello); // -1234.132
/*
格式化输出到文件
*/
// String outName = "out.txt"; // 保存hello : world
// File outFile = new File(outName);
// System.out.println(outFile.getAbsolutePath());
//
// PrintWriter printer = new PrintWriter(outFile); // FileNotFoundException
// printer.printf("%s : %s\n", "hello", "world");
// printer.close();
}
}