Java -- 键盘输入 Scanner, BufferedReader。 系统相关System,Runtime。随机数 Randrom。日期操作Calendar

1. Scanner 一个基于正则表达式的文本扫描器,他有多个构造函数,可以从文件,输入流和字符串中解析出基本类型值和字符串值。

public class Main {		
	public static void main(String[] args) throws FileNotFoundException {
		
		Scanner input = new Scanner(System.in);  //键盘输入
		input.useDelimiter("
");   //设置分隔符
		while(input.hasNext())   
		{			
			String tempStr = input.next();
			if(tempStr.equals("quit"))		
				break;
			else
				System.out.println("log1: " + tempStr);
		}
		
		while(input.hasNextLine())
		{
			String tempStr = input.nextLine();
			if(tempStr.equals("quit"))		
				break;
			else
				System.out.println("log2: " + tempStr);
		}	
	
		Scanner input2 = new Scanner(new File("/media/123.txt"));  //文件输入
		while(input2.hasNextLine())
		{
			System.out.println("FileLine: " + input2.nextLine());
		}		
	}	
}

2. Bufferedreader 是IO流中的一个字符包装流,必须建立在字符流的基础上,System.in 为字节流,需要InputStreamReader将其包装字符流。

BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
		String input2 = null;
		while( (input2=buffer.readLine())!=null )
		{
			System.out.println("input2: " + input2);
		}


 

比较两种键盘输入,不同的是Scanner还可以读入基本类型输入项,比如input.hasNextDouble(), 可以用Double tempStr = input.nextDouble(); 获得Double类型输入。

3. System 获取环境变量, Runtime获取运行时信息

	Map<String, String> env = System.getenv();  //获取环境变量
	for( String str : env.keySet() )
		System.out.println(str + "=" + env.get(str));
	
	Runtime rt = Runtime.getRuntime();   
	System.out.println(rt.availableProcessors()); //CPU个数
	System.out.println(rt.freeMemory()); //空余内存
	System.out.println(rt.totalMemory()); //总共内存
	System.out.println(rt.maxMemory()); //最大内存
	rt.exec("notepad.exe");   //windows下利用exec开启notepad


 4. 产生随机数

使用Math 和 Randrom类均可以,使用Random伪随机数时构造种子选当前时间 .

System.out.println("random: " + Math.random()*10);
	Random rd = new Random(System.currentTimeMillis());
	System.out.println(rd.nextBoolean());
	System.out.println(rd.nextDouble());
	System.out.println(rd.nextFloat());
	System.out.println(rd.nextInt());	


5. 日期操作Calendar类

Calendar cd = Calendar.getInstance(); //抽象类
	cd.setLenient(false);   //设置容错性
	System.out.println(cd.get(Calendar.YEAR));
	System.out.println(cd.get(Calendar.MONTH) + 1);
	System.out.println(cd.get(Calendar.DATE));
	cd.set(2013, 11-1, 11);
	System.out.println(cd.get(Calendar.YEAR));
	System.out.println(cd.get(Calendar.MONTH) + 1);
	System.out.println(cd.get(Calendar.DATE));
	cd.add(Calendar.YEAR, 1);
	System.out.println(cd.get(Calendar.YEAR));
	System.out.println(cd.get(Calendar.MONTH) + 1);
	System.out.println(cd.get(Calendar.DATE));


 


 

原文地址:https://www.cnblogs.com/xj626852095/p/3648077.html