输入算法总结

1.多组输入,每组输入共一行,包括两个整数A,B

Sample Input
1 2
12 24
400 500
Sample Output
3
36
900

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

2.第一行是数据的组数N,从第二行开始是N组数据有两个整数(A和B)构成的数据,A和B之间用空格隔开,每组输入独占一行

Sample Input
2
1 2
10 20
Sample Output
3
30

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     int n=sc.nextInt();
     while(n-->0) {
     System.out.println(sc.nextInt()+sc.nextInt());
     }
    }
}

3.多组数据:每组有两个整数(A和B)构成,A和B之间用空格隔开,每组输入单独占一行。当输入为“0 0”时,输入结束。“0 0”这组数据不处理。

Sample Input
1 2
3 4
10 20
0 0
Sample Output
3
7
30

//3
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     while(true) {
     int a=sc.nextInt();
     int b=sc.nextInt();
     if(a==0 && b==0)break;
     System.out.println(a+b);
     }
    }
}

4.输入包含多个测试用例。每个测试用例包含一个正整数N,随后是N个整数跟在同一行上。当某个测试用例以0开始,终止输入,且改用例不处理。

 Sample Input
3 1 2 4
1 23
5 1 3 5 7 9
0
Sample Output
7
23
25

//4
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     while(true) {
     int a=sc.nextInt();
     if(a==0)break;
     int ac=0;
     while(a-->0)ac+=sc.nextInt();
     System.out.println(ac);
     }
    }
}

5.第一行为N,下面紧跟N行数据。每行数据:开头为,后面紧跟M个数。

Sample Input
2
1 1
2 3 4
Sample Output
1
7

//5
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     int n=sc.nextInt();
     while(n-->0) {
     int a=sc.nextInt();
     if(a==0)break;
     int ac=0;
     while(a-->0)ac+=sc.nextInt();
     System.out.println(ac);
     }
    }
}

 

posted @ 2022-07-04 10:46  开源遗迹  阅读(86)  评论(0)    收藏  举报