java输入输出语句

Scanner sc=new Scanner(System.in);

int x=sc.next();//读入一个字符串,遇到空格,空格后的内容不会被读入

int y=sc.nextInt(); //读入一个整数

String  line=sc.nextLine();//读入一行,可以包括空格,换行符后的内容不会被读入

//另外还有:
float  y=sc.nextFloat();  //读入一个单精度浮点数
double z=sc.nextDouble(); //读入一个双精度浮点数

//读入一个字符:
char c=sc.next().charAt(0);


总结:直接next就是读一个字符串,nextInt就是读一个整数,nextFloat就是读一个单精度浮点数,nextDouble就是读一个双精度浮点数,nextLine就是读一行

快速读快速写:

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String  str=br.readLine();//读一行  

char  x=br.read();//读一个字符


BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));

bw.write("Hello World\n");

bw.flush();//刷新缓冲区

 核心是读入一个一维数组(读入二维数组不过是是读入多个一维数组罢了)

        Scanner sc=new Scanner(System.in);
        System.out.println("请输入a的值:");
        int a=sc.nextInt();

        System.out.println("请输入b的值:");
        int b=sc.nextInt();

        int c=a+b;

        System.out.println(c);
Scanner sc=new Scanner(System.in);

//输入字符串
String str=sc.next();
//上面的方法无法读入含有空格的字符串
//如果想要输入含有空格的字符串需要使用:String str=sc.nextLine();

//输入整数
int x=sc.nextInt();

//输入单精度浮点数
float y=sc.nextFloat();

//输入双精度浮点数
double z=sc.nextDouble();


// 输入单个字符
char z=sc.next().charAt(0);

 模式一:读入一个一维数组,数字与数字之间用空格分割

比如:

1 50 67 78 123 4 56
public class test
{
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);


        String string = scanner.nextLine();

        String[] array=string.split(" ");//将字符串按空格分割成字符数组

        //接下来将字符数组转换成整数数组
        int[] nums=new int [array.length];
        for(int i=0;i

总结:

step1:读入字符串(含有空格)

step2:将字符串转化为字符数组

step3:将字符数组转化成整数数组

模式二:输入二维数组,行数m,列数n都是已知:

第一行表示m

第二行表示n

接下来m行表示每一行的数据

比如:

3            
3          
1 3 4
1 3 5
2 4 6

 又比如说:

2
3
1 2 3
4 5 6
public class test
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();

        int n= scanner.nextInt();

        int[][] nums = new int[m][n];

        scanner.nextLine();//用来跳过行列后的回车符

        //读入m行数据
        for (int i = 0; i < m; i++)
        {
            String string = scanner.nextLine();

            String[] array=string.split(" ");//将字符串按空格分割成字符数组

            //接下来将字符数组转换成整数数组
            int[] temp=new int [array.length];
            for(int j=0;j

总结:先把行数m,列数n读进来

然后再读取m行数据即可(循环m次读取一维数组)

另外:用BufferedReader代替Scanner读入,用BufferedWriter代替println输出可以加快输入输出(当数据量特别大的时候不开快读快写可能会超时)

public class test
{
    public static void main(String[] args) throws IOException 
    {
        //快读
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
        bufferedReader.readLine();
        
        //快写
        BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(System.out));
        bufferedWriter.write("测试");
        
        //加到代码最后
        bufferedWriter.flush();
    }
}

你可能感兴趣的:(leetcode,leetcode)