java的ACM模式的输入输出、链表以及树的构建

1.java.util.Scanner包

  1. nextInt():直至读取到空格或回车之后结束本次的int值;
  2. next():直至读取到空格或回车之后结束本次的String值,不可读取回车;
  3. nextLine():直至读取到换行符(回车)之后结束本次读取的String,可读取回车(空值)

1.1 读取连续整数(两个整数a和b)

import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
            int a=in.nextInt();
            int b=in.nextInt();
            System.out.println(a+b);
        }
    }
}

1.2 每行读取空格隔开的整数

import java.util.Scanner;
import java.lang.String;
import java.lang.Integer;
public class Main{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
            String[] temp=in.nextLine().split(" ");
            int sum=0;
            for(String s:temp)
                sum+=Integer.valueOf(s);
            System.out.println(sum);
        }
    }
}

1.3 读取多行输入

import java.util.Scanner;

//		示例1
        // 输入
        // 5 10 9
        // 0 5
        // 9 1
        // 8 1
        // 0 1
        // 9 100
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();        // 5
        int full = sc.nextInt();        // 10
        int avg = sc.nextInt();        // 9
        sc.nextLine();
        int[][] nums = new int[n][2];
        for (int i = 0; i < n; i++) {
            nums[i][0] = sc.nextInt();
            nums[i][1] = sc.nextInt();

        }
    }
}

1.4 输入一个链表(以反转链表为例)

import java.util.Scanner;
import java.util.Stack;

public class LinkListInput {
    //题目描述
    //对于一个链表 L: L0→L1→…→Ln-1→Ln,
    //将其翻转成 L0→Ln→L1→Ln-1→L2→Ln-2→…

	//先构建一个节点类,用于链表构建
    static class LinkNode {
        int val;
        LinkNode next;
        public LinkNode(int val){
            this.val = val;
        }
    }
    
	public static void main(String[] args){
        //输入是一串数字,请将其转换成单链表格式之后,再进行操作
        //输入描述:	一串数字,用逗号分隔
        //输入
        //1,2,3,4,5
        Scanner scanner = new Scanner(System.in);
        //以字符串形式作为输入
        String str = scanner.next().toString();
        //通过分隔符将其转为字符串数组
        String[] arr  = str.split(",");
        //初始化一个整数数组
        int[] ints = new int[arr.length];
        //给整数数组赋值
        for(int j = 0; j<ints.length;j++) {
            ints[j] = Integer.parseInt(arr[j]);
        }
        
		Stack<LinkNode> stack = new Stack<>();
        LinkNode head = new LinkNode(0);
        LinkNode p = head;
		
		//链表初始化并放入stack中
        for(int i = 0; i < ints.length; i++){
            p.next = new LinkNode(ints[i]);
            p = p.next;
            stack.add(p);
        }
        head = head.next;
        //开始链表转换
        p = head;
        LinkNode q = stack.peek();
        while ((!p.equals(q)) && (!p.next.equals(q))) {
            q = stack.pop();
            q.next = p.next;
            p.next = q;
            p = p.next.next;
            q = stack.peek();
        }
        q.next = null;
		 //输出
        //1,5,2,4,3
        //打印
        while (head != null) {
            if(head.next == null){
                System.out.print(head.val);
            }else{
                System.out.print(head.val + ",");
            }
            head = head.next;
        }
    }
}

1.5 输入一个二叉树(层序遍历)

import java.util.*;

public class Tree {
   static class TreeNode{
      int val;
      TreeNode left;
      TreeNode right;
      public TreeNode(){}
      public TreeNode(int val){
         this.val = val;
      }
   }
	//方法入口
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      String s = scanner.nextLine();
      String[] split = s.split(" ");
      int[] arr = new int[split.length];
      for(int i = 0; i < arr.length; i++){
         arr[i] = Integer.parseInt(split[i]);
      }
      //构建二叉树
      TreeNode root = build(arr);
      //层序遍历二叉树
      List<List<Integer>> res = help(root);
      //打印结果
      for (List<Integer> ans : res){
         System.out.print(ans);
      }
   }
   //层序遍历二叉树
   private static List<List<Integer>> help(TreeNode root) {
      List<List<Integer>> res = new ArrayList<>();
      LinkedList<TreeNode> queue = new LinkedList<>();
      queue.add(root);
      while(queue.size() > 0){
         List<Integer> tmp = new ArrayList<>();
         int size = queue.size();
         for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            tmp.add(node.val);
            if(node.left != null){
               queue.add(node.left);
            }
            if(node.right != null){
                  queue.add(node.right);
            }
         }
         res.add(tmp);
      }
      return res;
   }
   //构建二叉树
   private static TreeNode build(int[] arr) {
      List<TreeNode> list = new ArrayList<>();
      Collections.fill(list, null);
      TreeNode root = null;
      for(int i = 0; i < arr.length; i++){
         TreeNode node = null;
         if(arr[i] != -1){
            node = new TreeNode(arr[i]);
         }
         list.add(i,node);
         if(i == 0){
            root = node;
         }
      }
      for (int i = 0;  2 * i + 2 < arr.length ; i++) {
         if(list.get(i) != null){
            list.get(i).left = list.get(2 * i + 1);
            list.get(i).right = list.get(2 * i + 2);
         }
      }
      return root;
   }

}

1.6 多行输入多个参数,每行参数个数不定

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main{
    /**
     * 输入如下
     * 3
     * 1 2 3 4
     * 2 3
     * 1
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        sc.nextLine();
        String[] s = new String[m];
        for (int i = 0; i < m; i++) {
            s[i] = sc.nextLine();
        }
        List<String[]> list = new ArrayList<>();
        for (int i = 0; i < s.length; i++) {
            String[] s1 = s[i].split(" ");
            list.add(s1);
        }

        List[] res = new List[list.size()];
        for (int i = 0; i < list.size(); i++) {
            String[] strings = list.get(i);
            res[i] = new ArrayList();
            for (String c : strings) {
                res[i].add(Integer.parseInt(c));
            }
        }

        System.out.println(Arrays.deepToString(res));
    }


}
  

1.7 输入数组中带有中括号和逗号

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<List<Integer>> list = new ArrayList<>();
        while (sc.hasNextLine()) { //每行都是一个List数组
            List<Integer> line = new ArrayList<>();
            String str = sc.nextLine();
            String[] arr = str
                    .replace("[","")
                    .replace("]","")
                    .replace("],","")
                    .replace(" ","")
                    .split(","); //只要改这里就可以,加几个replace()
            for (String s : arr) {
                line.add(Integer.valueOf(s));
            }
            list.add(line);
        }
        System.out.println(list); //[[3, 2, 3], [1, 6, 5], [7, 8, 9]]
    }
}

1.8 输入链表

// 输入是一串数字,用逗号分隔(1,2,3,4,5),请将其转换成单链表格式之后,再进行操作。
import java.util.Scanner;
import java.util.Stack;
public class Main {
    static class LinkNode {
        int val;
        LinkNode next;
        public LinkNode(int val){
            this.val = val;
        }
    }
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        //以字符串形式作为输入
        String str = scanner.next().toString();
        //通过分隔符将其转为字符串数组
        String[] arr  = str.split(",");
        //初始化一个整数数组
        int[] ints = new int[arr.length];
        //给整数数组赋值
        for(int j = 0; j<ints.length;j++) {
            ints[j] = Integer.parseInt(arr[j]);
        }

        LinkNode head = new LinkNode(0);
        LinkNode p = head;
        //链表初始化并放入stack中
        for(int i = 0; i < ints.length; i++){
            p.next = new LinkNode(ints[i]);
            p = p.next;

        }
}

2. 使用 BufferedReader和InputStreamReader

2.1 导包

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main {
    public static void main(String[] args) throws IOException{
    	......
    }
}

2.2 输入为一个字符串时

        // 创建一个BufferedReader对象
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 读取字符串    abc
        String line = br.readLine();
 
        // 测试输入是否正确
        System.out.println(line);

2.3 输入为多个数字

        // 创建一个BufferedReader对象
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 读取第一行数据
        String line = br.readLine();    // 1 2
        // 将字符串根据空格进行分隔
        String[] strings = line.trim().split(" ");
        // 分别将其中的每个数值读出
        int n = Integer.parseInt(strings[0]);
        int v = Integer.parseInt(strings[1]);
 
        // 测试输入是否正确
        System.out.println("n: " + n + "\tv: " + v);  // n:1  v: 2

2.4 输入一个数组且已知长度

        // 创建一个BufferedReader对象
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 读取第一行数据
        String line = br.readLine();
        // 将字符串根据空格进行分隔
        String[] strings = line.trim().split(" ");
        // 分别将其中的每个数值读出
        int n = Integer.parseInt(strings[0]);
        int v = Integer.parseInt(strings[1]);
        // 读取第二行数据
        line = br.readLine();
        strings = line.trim().split(" ");
        // 创建一个int型的数组用来储存第二行的多个数字
        int[] nums = new int[n];
        for (int i = 0; i < n; i ++) {
            nums[i] = Integer.parseInt(strings[i]);
        }
 
        // 测试输入是否正确
        for (int num: nums) {
            System.out.print(num + " ");
        }

3.输出写法

System.out.println(); //换行打印,输出之后会自动换行
System.out.print(); //不换行打印
System.out.printf(); //按格式输出

对于System.out.printf()函数:

/*** 输出字符串 ***/
// %s表示输出字符串,也就是将后面的字符串替换模式中的%s
System.out.printf("%s", new Integer(1212));
// %n表示换行
System.out.printf("%s%n", "end line");
// 还可以支持多个参数
System.out.printf("%s = %s%n", "Name", "Zhangsan");
// %S将字符串以大写形式输出
System.out.printf("%S = %s%n", "Name", "Zhangsan");


/*** 输出整数类型***/
Integer iObj = 342;
// %d表示将整数格式化为10进制整数
System.out.printf("%d; %d; %d%n", -500, 2343L, iObj);
// %o表示将整数格式化为8进制整数
System.out.printf("%o; %o; %o%n", -500, 2343L, iObj);
// %x表示将整数格式化为16进制整数
System.out.printf("%x; %x; %x%n", -500, 2343L, iObj);
// %X表示将整数格式化为16进制整数,并且字母变成大写形式
System.out.printf("%X; %X; %X%n", -500, 2343L, iObj);

/*** 输出浮点类型***/
Double dObj = 45.6d;
// %f表示以十进制格式化输出浮点数
System.out.printf("%f; %f; %f%n", -756.403f, 7464.232641d, dObj);
// 还可以限制小数点后的位数
System.out.printf("%.1f; %.3f; %f%n", -756.403f, 7464.232641d, dObj);
  • 16
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值