> 其他 >
编写java程序,输入个数不定的整数,输入0时结束.统计这些整数中正数和负数的个数,并计算它们的总和.
人气:296 ℃ 时间: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 函数中调用即可
推荐
猜你喜欢
© 2024 79432.Com All Rights Reserved.
电脑版|手机版