作业帮 > 综合 > 作业

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

来源:学生作业帮 编辑:搜搜考试网作业帮 分类:综合作业 时间:2024/04/30 21:38:13
编写java程序,输入个数不定的整数,输入0时结束.统计这些整数中正数和负数的个数,并计算它们的总和.
编写java程序,输入个数不定的整数,输入0时结束.统计这些整数中正数和负数的个数,并计算它们的总和.
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 函数中调用即可