Programming questions: data statistics in complex situations-hebust(Java)

When performing numerical statistics, some non-numerical elements may be mixed in. Please program to complete the summation of the input sequence and output it. If non-numerical elements are encountered, it will be automatically skipped and start after the final result output line. One line, output attention.
Input format:
single line input, separated by spaces between elements.
Output format:
sum the integers corresponding to the elements and output.
If a non-numeric element is encountered, it will be automatically skipped and another line will be added after the final result output line Start a line and output attention

Input example a:
Here is a set of inputs. For example:
1 2 3 4 5
Output sample a:
The corresponding output is given here. For example:
15

Input example b:
Here is a set of inputs. For example:
1 2 3 4 a 5
Output sample b:
The corresponding output is given here. For example:
15
attention

import java.util.Scanner;

public class Main{
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int flag = 0 , sum=0;
		String s = sc.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) {
    
    
        		flag=1 ;
        		continue;
        	} 
		}
		System.out.println(sum);
		if(flag==1) {
    
    
			System.out.println("attention");
		}
	}
}

Guess you like

Origin blog.csdn.net/weixin_51430516/article/details/115119228