0
点赞
收藏
分享

微信扫一扫

【面试算法题总结01】输入输出处理基础

左手梦圆 2022-02-26 阅读 47

输入输出处理基础:

并不是所有公司的机试环境都是“核心代码模式”,有些是“ACM模式”,需要自己写输入输出处理。
 

1 特定个数输入

/**数组求和 一直输入
1 5
10 20
6
30* */

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

2 不定个数输入

/** 数组求和 直接求 一直输入
1 2 3
4 5
0 0 0 0 0
6
9
0 */
import java.util.*;

class Solution{
    public void f(){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int sum=0;
            String[] temp=sc.nextLine().split(" ");
            for(int i=0;i<temp.length;++i){
                sum+=Integer.valueOf(temp[i]);
            }
            System.out.println(sum);
        }
    }
}
public class Main{
    public static void main(String[] args){
        new Solution().f();
    }
}

3 特定个数字符串输入

/** 给出个数,下例5为个数
 5
 c d a bb e
 5
 c d a bb f
 
 a bb c d e
 a bb c d f*/
import java.util.*;

class Solution{
    public void f(){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int n=sc.nextInt();
            String[] temp=new String[n];
            for(int i=0;i<n;++i){
                temp[i]=sc.next();
            }
            Arrays.sort(temp);
            System.out.println(String.join(" ",temp));
        }
    }
}
public class Main{
    public static void main(String[] args){
        new Solution().f();
    }
}

4 不定个数字符串输入

/** 一直输入
 a c bb
 f dddd
 nowcoder
 
 a bb c
 dddd f
 nowcoder*/
import java.util.*;

class Solution{
    public void f(){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String[] temp=sc.nextLine().split(" ");
            Arrays.sort(temp);
            //输出方法1:
            System.out.println(String.join(" ",temp));
            //输出方法2:
            StringBuilder result=new StringBuilder("");
            for(int i=0;i<temp.length;++i){
                result.append(" ");
                result.append(temp[i]);
            }
            System.out.println(result.toString().trim());
        }
    }
}
public class Main{
    public static void main(String[] args){
        new Solution().f();
    }
}
举报

相关推荐

0 条评论