ACM 输入输出

356 阅读1分钟

Java Acm输入模式

总体思路

  1. 创建Scanner对象
Scanner s = new Scanner(System.in);
  1. 在输入之前,可以先判断是否还有输入的数据,例如,判断字符串,可以用 hasNext与hasNextLine
while(s.hasNextLine()){

}
  1. 接受数据
String str = s.nextLine();
String str= s.next();
  1. 然后接下来就可以利用这个数据进行操作了 其他的整形,浮点型数据形式差不多 输出就直接
System.out.printn();

next() 和 nextLine()的区别:
1、next()会自动消去有效字符前的空格,只返回输入的字符,不能得到带空格的字符串
2、nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
3、next()在输入有效字符之后,将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符

1.有些输入可能是: 输入一个矩阵,每行以空格分隔。

3 2 3
1 6 5
7 8 9
public static void main(String args[])
  {
    Scanner cin = new Scanner(System.in);
    ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
    while(cin.hasNextLine())
    {
      ArrayList<Integer> row = new ArrayList<Integer>();
      String line = cin.nextLine();
      if (line.length() > 0) {
        String[] arrLine = line.split(" ");//分割空格
        for (int i=0; i<arrLine.length; i++) {
          row.add(Integer.parseInt(arrLine[i]));//字串转整数
        }
        arr.add(row);
      }
    }
    else {
        break;
    }
  }
  for (int i = 0; i < arr.size(); i++) {//遍历list数组
      for (int j = 0; j < arr.get(i).size();j++) {//遍历list中每个元素
        System.out.println(arr.get(i).get(j));
    }

}

2.有些输入可能是,输入一个矩阵:

[[3,2,3], 
[1,6,5], 
[7,8,9]]
public static void main(String args[])
  {
    Scanner cin = new Scanner(System.in);
    ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
    while(cin.hasNextLine())//判断是否还有行
    {
      ArrayList<Integer> row = new ArrayList<Integer>();
      String line = cin.nextLine().trim();//去掉首尾空格 读取每行的数据
      if (line.length() > 0) {
        String[] arrLine = line
          .replace("],", "")
          .replace(" ", "")//去除所有空格,包括首尾、中间
          .replace("[", "")
          .replace("]", "")
          .split(",");

        for (int i=0; i<arrLine.length; i++) {
          row.add(Integer.parseInt(arrLine[i]));
        }
        arr.add(row);
      }
    }