Java笔试: ACM模式处理输入输出 大部分公司都会使用牛客网来进行笔试,当然其中和我们常刷题的leetcode有个重要的不同点就是程序的输入和输出。leetcode模式不需要我们自己去输入测试用例,而是封装一个Solution类由系统调用。而ACM模式则需要我们编写代码手动输入程序的参数和输出程序的结果。
输入 基本的框架可以如下方式构建:
1 2 3 4 5 6 7 8 9 10 import  java.util.Scanner;public  class  Main public  static  void  main (String[] args) new  Scanner(System.in);
在上述步骤二中,我们需要根据题目来自定义输入格式,比如:
读取一个整数
1 2 3 4 
读取一个字符或者字符串
读取一个浮点数
1 2 3 4 
读取一整行(返回String)
循环读取
有些题目会设置循环读取参数,判断是否还有下一个输入可以用:
如果题目中没有说明一次给几个输入,为了保险起见可以直接用while(cin.hasNext()){}将输入包括起来。
或者就是根据题目设定,先读取数据组数,再设定循环处理数据(如下方例1)
 
其中next()方法读取到空白符就结束,但是nextLine()读取到回车结束也就是‘\t’。
 
如果要在next(), nextDouble(), nextFloat(), nextInt()等语句之后使用nextLine()时,需要再加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。 
1 2 3 4 5 6 7 8 9 10 11 public  class  Main public  static  void  main (String[] args) new  Scanner(System.in);int  num1 = cin.nextInt();int  nums2 = cin.nextInt();
输出 1 2 3 4 5 6 7 8 "%.2f" ,1.23 );"这是换行符%n" );  
例1 重复固定位数的参数 以牛客网[AB28 快速幂][https://www.nowcoder.com/practice/defdedf4fe984c6c91eefa6b00d5f4f0?tpId=308&tqId=2403107&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Ftab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308]为例,第一个数输入为调用方法的次数,也就是执行q组参数,但是输入参数个数是固定的3个: 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 输入: 2 2  2  6 3  4  10 4 1 import  java.util.Scanner;public  class  Main  public  static  void  main (String[] args)  new  Scanner(System.in);long  q = cin.nextInt();for (int  i = 0 ;i < q;i++){long  a = cin.nextInt();long  b = cin.nextInt();long  p = cin.nextInt();
例2 读取二维数组 为了读取题目要求的二维数组,我们应该先读取二维数组的长度和宽度存在两个整数中。在下一行将一串整型数字存入二维数组中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 输入: 3  4 1  2  3  4 5  6  7  8 1  2  3  4 new  Scanner(System.in);while (cin.hasNext()) {int  r = cin.nextInt();int  c = cin.nextInt();int [][] matrix = new  int [r][c];for (int  i=0 ;i<r;i++) {for  (int  j = 0 ; j < c; j++) {