Java分配。找到min,奇数和的整数,以及负整数的数

时间:2016-10-30 07:10:35

标签: java

当用户输入数字列表时,输出基本上会告诉最小整数,奇数和的整数和负整数的数量(当用户输入0时停止)。我得到负数的计数是正确的但我遇到的问题是奇数整数的总和只在数字为正且最小整数总是0时才加。 这是我的代码

package example2;
import java.util.Scanner;
public class ex {

public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);
int oddsum=0, min=0, negcount=0;
int number;
do
{

number=sc.nextInt();

    if(number< 0)
     {

        negcount++;

     }
    else if(number%2!=0)
     {
         oddsum+=number;
     }
    else if(number<min)
     {
         number=min;
    }

}while(number!=0);
 System.out.println("The minimum integer is "+min);
 System.out.println("The sum of odd integers is "+oddsum);
 System.out.println("The count of negative integers in the sequence is "+negcount);


}
}

2 个答案:

答案 0 :(得分:0)

您正在使用if-else结构,这意味着只会执行其中一个分支。相反,您应该使用单独的if语句并分别评估每个条件:

if (number< 0) {
    negcount++;
}

if (number % 2 != 0) {
    oddsum += number;
}

if (number < min) {
    min = number;
}

答案 1 :(得分:0)

package example2; 
import java.util.Scanner; 
public class ex { public static void 
main(String[] args)
{ 
Scanner sc = new     
Scanner(System.in);
int oddsum=0, min=0, negcount=0; 
int number; 
do 
{
number=sc.nextInt(); 
if(number< 0) 
{ 
negcount++; 
}
if(number%2!=0)
{
 oddsum+=number;
}
if(number<min) 
{ 
min=number; 
} 
}while(number!=0); 

System.out.println("The minimum 
integer is "+min);     

System.out.println("The sum of odd
integers is "+oddsum);   

System.out.println("The count of    
negative integers in the sequence is
"+negcount); 
}
}

另请参阅 How does java do modulus calculations with negative numbers?