因为有的题目会要求可以处理多组输入,所以这里给出的解决方案都是兼容多组样例输入的
例题1(a+b)
输入
1 5
10 20输出
6
30
import java.util.*;
public class Main{
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
while(in.hasNextInt())
{
int a=in.nextInt();
int b=in.nextInt();
System.out.println(a+b);
}
}
}
例题2(给出组数的a+b)
输入
2
1 5
10 20输出
6
30
import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
while(in.hasNextInt())
{
int num=in.nextInt();
for(int i=0;i<num;i++)
{
int a=in.nextInt();
int b=in.nextInt();
System.out.println(a+b);
}
}
}
}
例题3(给出结束标志的a+b)
输入
1 5
10 20
0 0输出
6
30
import java.util.*;
public class Main{
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
while(in.hasNextInt())
{
int a=in.nextInt();
int b=in.nextInt();
if(a!=0 && b!=0)
System.out.println(a+b);
}
}
}
例题4(给出结束标志和长度的数组求和)
输入
4 1 2 3 4
5 1 2 3 4 5
0输出
10
15
import java.util.*;
public class Main{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while(in.hasNextInt())
{
int num=in.nextInt();
if(num==0) continue;
int[] a=new int[num];
for(int i=0;i<num;i++)
a[i]=in.nextInt();
add(a);
}
}
public static void add(int[] a)
{
int res=0;
for(int i=0;i<a.length;i++)
res+=a[i];
System.out.println(res);
}
}
例题5(数组求和)
输入
1 2 3 4
1 2 3 4 5输出
10
15
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String[] strs = sc.nextLine().split(" ");
int sum = 0;
for(int i=0;i<strs.length;i++){
sum += Integer.parseInt(strs[i]);
}
System.out.println(sum);
}
}
}
例题6(给出组数的字符串排序)
输入
5
c d a bb e输出
a bb c d e
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
// 注意nextLine()的坑,如果用nextInt()读取组数,用nextLine()读取字符串的话,组数后的回车换行会被读取到nextLine()里,因此组数要用下边的读法
// int n = Integer.parseInt(sc.nextLine());
// String str = sc.nextLine();
// String[] strs = str.split(" ");
int n =sc.nextInt();
String[] strs =new String[n];
for(int i=0;i<n;i++)
strs[i]=sc.next();
Arrays.sort(strs);
for(int i=0;i<strs.length-1;i++)
System.out.print(strs[i]+" ");
System.out.println(strs[strs.length-1]);
}
}
}