2014-09-18 2 views
-1
public class Exercise_442 { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 

    int count=0; 
    int positive=0; 
    int negative =0; 
    int nums=0; 
    int sum=0; 

    Scanner keyboard = new Scanner(System.in); 
    System.out.println("Pleaes enter a positive or negative integer"); 
    nums = keyboard.nextInt(); 


    while(nums!=0){ 
     sum+=nums; 
     System.out.println("Plese enter a positive or negative integer"); 
     nums = keyboard.nextInt(); 

     if(nums<0) 
      negative++; 

     if (nums>0) 
      positive++; 

    } 
    System.out.println("The sum of these numbers is " +sum); 
    System.out.println("The amount of negative numbers here is " + negative); 
     System.out.println("The amount of positive numbers here is " + positive); 
    } 
    } 

여기에 양수와 음수를 입력해야합니다. 이것은 사용자가 0을 입력 할 때 이것을 표시합니다. 음수를 확인하고 합계를 얻지 만 양의 정수를 계산할 때 왜 하나의 숫자가 부족한 지 알 수 없습니까?개수 양수 및 음수

답변

2

while 루프를 처음 입력 할 때 +/-의 첫 번째 숫자는 무시됩니다.

1을 nums으로 입력한다고 가정 해 봅시다. 합계에 1을 더한 다음> 또는 <을 평가하지 않고 새 입력을 요청합니다.

if 문을 while 루프의 nums = keyboard.nextInt(); 위로 이동하십시오.

while(nums!=0){ 
     sum+=nums; 

     //moved everything up before we pull nextInt 
     if(nums<0) 
      negative++; 

     if (nums>0) 
      positive++; 

     System.out.println("Plese enter a positive or negative integer"); 
     nums = keyboard.nextInt(); 

    } 
+2

두 번째'nums = keyboard.nextInt();'입니다. – Hungry

+0

@ btrs20 감사합니다. 내 대답에 전체 방법을 추가하여 명확하게했습니다. – Compass

관련 문제