题目:
复杂环境下的数据统计问题
进行数值统计的时候,可能会混入一些非数值的元素,下面请编程完成对输入序列进行求和统计并输出,
如果遇到非数值元素,则自动跳过,并在最终结果输出行之后另起一行,输出attention
输入格式:
单行输入,元素之间使用空格分开
输出格式:
对元素所对应的整数进行求和并输出
如果遇到非数值元素,则自动跳过,并在最终结果输出行之后另起一行,输出attention
输入样例a:
在这里给出一组输入。例如:
1 2 3 4 5
输出样例a:
在这里给出相应的输出。例如:
15
输入样例b:
在这里给出一组输入。例如:
1 2 3 4 a 5
输出样例b:
在这里给出相应的输出。例如:
15
attention
答案1:遍历每个字符判断有无非数值元素
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String s=in.nextLine();
String[] str=s.split(" ");
int[] b=new int[str.length];
int sum=0;
int i=0;
for(int k=0;k<str.length;++k)
{
char[] a=new char[1001];
int t=0;
for(int j=0;j<str[k].length();++j)
{
a[j]=str[k].charAt(j);
if(a[j]>'9'||a[j]<'0')
{
t=1;
i=1;
}
}
if(t==0)
{
//b[k]=Integer.parseInt(str[k]);
b[k]=Integer.valueOf(str[k]);
sum+=b[k];
}
}
System.out.print(sum);
if(i==1)
{
System.out.println();
System.out.print("attention");
}
}
}
答案2:异常捕捉判断有无非数值元素
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int t=0,sum=0;
Scanner input=new Scanner(System.in);
String s=input.nextLine();
String[] str=s.split(" ");
for(int i=0;i<str.length;i++)
{
try
{
int num = Integer.valueOf(str[i]);
sum+=num;
}
catch (Exception a)
{
t=1 ;
continue;
}
}
System.out.println(sum);
if(t==1)
System.out.println("attention");
}
}
总结:
掌握字符串转字符串数组,字符串数组转整数,字符串及字符串数组转字符数组。
String s = in.nextLine();
String[] str = s.split(" ");
int[] b=new int[str.length];
b[k]=Integer.parseInt(str[k]);
b[k]=Integer.valueOf(str[k]);
char[] a = new char[1001];
a[j]=str[k].charAt(j);