牛客网输入方法

2019-08-13  本文已影响0人  Reinelili

常常遇到多行输入,给定的是一行用空格隔开的数字:

1 2 3 4 5 6 7 8 9

获取方法有两种:

  1. 循环获取
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int i = 0; i < n; i++){
   int a = scanner.nextInt();
   int b = scanner.nextInt();
   System.out.println(a+b);
}
  1. 获取一行string 然后分割
import java.util.*;
import java.io.*;
public class Main{
    public static void main(String[]args) throws Exception{
            InputStreamReader ir = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(ir);
            String[] str = br.readLine().split(" ");
            Set<String> set = new HashSet<>();

            for(int i=0;i<str.length;i++){
                if(!set.contains(str[i])){
                    set.add(str[i]);
                }else{
                    System.out.println(str[i]);
                    break;
                }
            }//for 
    }
  
}
import java.util.*;
public class Main{
    public void main(String arg[]){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String[] splited = str.split(" ");
        int length = splited.length;
        List<String> listCopy = new ArrayList<>();
        
        for (int i = 0; i< length; i++){
            if(!listCopy.contains(splited[i])){
               listCopy.add(splited[i]);
            }
            else{
                System.out.print(splited[i]);
                break;
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读