JQInputData工具类
package Scanner;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class JQInputData {
public static Scanner scan = new Scanner (System.in);
/**从键盘获取字符串*/
public static String getString(String info){
Scanner scan = new Scanner (System.in);
scan.useDelimiter("\n");//设置结束标识为换行,不然字符串没有办法加入空格
System.out.println(info);
String str = null;
str = scan.next();
return str;
}
/**从键盘获取int类型数据*/
public static int getInt(String info,String err) throws IOException{
boolean flag = true;
int tmp = 0;
while(flag){
System.out.println(info);
if(scan.hasNextInt()){
tmp = scan.nextInt();
flag = false;
}else{
System.out.println(err);
scan.next(); //如果不满足,那么一定要用scan.next()把刚才输入的内容接收了,不然会无休止判断下去
}
}
return tmp;
}
/**从键盘获取float类型数据*/
public static float getFloat(String info,String err){
boolean flag = true;
float tmp = 0;
while(flag){
System.out.println(info);
if (scan.hasNextFloat()){
tmp = scan.nextFloat();
flag = false;
}else{
System.out.println(err);
scan.next();
}
}
return tmp;
}
/**从键盘获取日期(2016-06-30)转成Date对象*/
public static Date getDate(String info,String err) throws ParseException{
boolean flag = true;
Date tmp = null;
while(flag){
System.out.println(info);
if (scan.hasNext("([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))")){
String str = scan.next("([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))");
tmp = new SimpleDateFormat("yyyy-MM-dd").parse(str);
flag = false;
}else{
System.out.println(err);
scan.next();
}
}
return tmp;
}
}
Test
package Scanner;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("您输入的文本是:"+JQInputData.getString("\n请输入文本:"));
System.out.println("您输入的整数是:"+JQInputData.getInt("\n请输入整数:","不对,请重新输入:"));
System.out.println("您输入的浮点数是:"+JQInputData.getFloat("\n请输入浮点数:","不对,请重新输入:"));
}
}
Test2
package Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import File.JQPathTool;
public class Test2 {
public static void main(String[] args) throws FileNotFoundException {
String path = JQPathTool.getPath(JQPathTool.Desktop + "/io.txt");
File f = new File(path);
Scanner scan = new Scanner(f); // 这里来源是File 不能填Path,否则会对路径字符串进行读取
StringBuffer buf = new StringBuffer();
while (scan.hasNext()) {
buf.append(scan.next()).append("\n");
}
System.out.print(buf);
}
}