2014-09-18 3 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 выше nums = keyboard.nextInt(); в цикле while.

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(); 'that. – Hungry

+0

@ btrs20 Спасибо. Я добавил весь метод к моему ответу, чтобы сделать его более ясным. – Compass

Смежные вопросы