编写java程序,输入个数不定的整数,输入0时结束.统计这些整数中正数和负数的个数,并计算它们的总和.

编写java程序,输入个数不定的整数,输入0时结束.统计这些整数中正数和负数的个数,并计算它们的总和.
其他人气:937 ℃时间:2019-09-20 06:18:58
优质解答
public static void test(){
Scanner sc = new Scanner(System.in);
long num = 0,negative = 0,positive = 0,sum = 0;
List nums = new ArrayList();
do{
System.out.println("please enter a number :");
String s = sc.nextLine();
if (isNumber(s)) {
num = Long.parseLong(s);
if(num != 0){
nums.add(num);
continue;
}
break;
}
System.out.println("not number !");
break;
}while(true);
for (Long n :nums) {
if(n > 0){
positive ++;
}else{
negative ++;
}
sum += n;
}
System.out.println("the negative :" + negative);
System.out.println("the positive :" + positive);
System.out.println("the sum :" + sum);
}
public static boolean isNumber(String s){
try {
Long.parseLong(s);
return true;
} catch (Exception e) {
return false;
}
}
在 main 函数中调用即可
我来回答
类似推荐
请使用1024x768 IE6.0或更高版本浏览器浏览本站点,以保证最佳阅读效果。本页提供作业小助手,一起搜作业以及作业好帮手最新版!
版权所有 CopyRight © 2012-2024 作业小助手 All Rights Reserved. 手机版