输入输出
输入
我知道的有三种,分别是Scanner、BufferedReader、StreamTokenizer。
比较:
运行速度:Scanner > BufferedReader > StreamTokenizer;
占用内存:Scanner > BufferedReader > StreamTokenizer;
代码实现如下:(输入二维数组)
//Scannner
import java.io.*;
import java.util.*;
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int arr[][] = new int[n][m];
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
arr[i][j] = sc.nextInt();
}
}
//BufferedReader
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]), m = Integer.parseInt(line[1]);
int[][] arr= new int[n][m];
for ( int i = 0; i < n; i++ ) {
line = br.readLine().split(" ");
for ( int j = 0; j < m; j++ ) {
arr[i][j] = Integer.parseInt(line[j]);
}
}
//StreamTokenizer
Input in = new Input();
int n = in.nextInt();
int m = in.nextInt();
int arr[][] = new int[n][m];
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
int[i][j] = in.nextInt();
}
}
//输出
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < m; j++ ) {
System.out.print(arr[i][j] + " ");
}
}
class Input
{
StreamTokenier st = new StreamTokenier(new BufferedReader(new InputStreadReader(System.in)));
public int nextInt()throws IOException
{
in.nextToken();
return (int)in.nval;
}
}
}
输出
我知道的有三种,分别是直接System.out.println输出、使用StringBuilder缓冲后输出、PrintWriter输出。
比较:
运行时间:System.out.println > PrintWriter >StringBuilder
占用内存:StringBuilder > PrintWriter > System.out.println
代码实现:
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws IOException {
// 优化输入
Input in = new Input();
int n = in.nextInt(), m = in.nextInt();
int[][] nums = new int[n][m];
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < m; j++ ) {
nums[i][j] = in.nextInt();
}
}
// 直接输出
for ( int i = m-1; i >= 0; i-- ) {
for ( int j = 0; j < n; j++ ) {
System.out.print(nums[j][i]+" ");
}
System.out.println();
}
// StringBuilder缓冲输出
StringBuilder sb = new StringBuilder();
for ( int i = m-1; i >= 0; i-- ) {
for ( int j = 0; j < n; j++ ) {
sb.append(nums[j][i]+" ");
}
sb.append("\r\n");//换行
}
System.out.println(sb.toString());
// PrintWriter输出
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
for ( int i = m - 1; i >= 0; i-- ) {
for ( int j = 0; j < n; j++ ) {
out.print(nums[j][i] + " ");
}
out.println();
}
out.flush();
}
}
class Input {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
}