复杂情况下的数据统计问题

题目:

复杂环境下的数据统计问题

进行数值统计的时候,可能会混入一些非数值的元素,下面请编程完成对输入序列进行求和统计并输出,
如果遇到非数值元素,则自动跳过,并在最终结果输出行之后另起一行,输出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);

   

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值