1

I have to make a program that allows the user to enter integer numbers until he press '0'. The program has to print: 1)The total number of the entered numbers 2) The number of the positive ones 3) The average of the positive ones 4) The number of the negative ones 5) The sum of the negatives

So far, all I could do is make the "enter untill '0' is pressed" and find the number of the entered numbers, which is a lot for me and my programing skills. I am having troubles trying to find out if the number is positive or negative. Probably I am not comparing them right, so I would love if I get a little help from someone advanced.

Here's my code so far:

import java.io.*; 

class Nums { 
  public static void main(String args[])  
    throws IOException 
  { 
    BufferedReader br = new BufferedReader(new 
                            InputStreamReader(System.in)); 
    String str;
    int EnteredNumbers = -1;
    int Positive = 0;
    int Negative = 0;
    int NegativeSum = 0;
    double AveragePositive = 0;

    System.out.println("Enter '0' to quit."); 
    System.out.println("Enter Numbers: "); 
    do { 
      EnteredNumbers++;
      str = br.readLine();

    } while(!str.equals("0")); 
      System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
      System.out.println("You have have entered "+Positive+ " Positive numbers!");
      System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
      System.out.println("You have have entered "+Negative+ " Negative numbers!");
      System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
  } 
}
Monster
  • 21
  • 1
  • 7
  • `boolean isNeg=false; if(str.startsWith("-")){ str=str.substring(1); isNeg=true; } int NUMBER=Integer.parseInt(str); if(isNeg) { NUMBER*=-1; }` Something like this ? – Charlie Dec 19 '14 at 16:06
  • 1
    Btw, be careful about good practices to name variables. They shouldn't be Capital – user7197 Dec 19 '14 at 16:08

7 Answers7

2

Firstly as pointed out Integer.parseInt is used in java to convert from String to int. Secondly you need to have a extra variable to store and accumulate the total of positive numbers too. I have added a try-catch exception block to handle errors.

Here is a code for reference.

import java.io.*; 

public class Nums { 
  public static void main(String args[])  
    throws IOException 
  { 
    BufferedReader br = new BufferedReader(new 
                            InputStreamReader(System.in)); 
    String str;
    int EnteredNumbers = -1;
    int Positive = 0;
    int Negative = 0;
    int NegativeSum = 0;
    int PositiveSum = 0; // Added extra variable
    double AveragePositive = 0;

    System.out.println("Enter '0' to quit."); 
    System.out.println("Enter Numbers: "); 
   try{
    do { 
      EnteredNumbers++;
      str = br.readLine();

    int num = Integer.parseInt(str);


    if (num>0)
      {
        Positive++;
        PositiveSum+=num;
      }
      else if (num<0)
      {
        Negative++;
        NegativeSum+=num;
      }
    } while(!str.equals("0")); 
    AveragePositive = (double)PositiveSum/(double)Positive;
      System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
      System.out.println("You have have entered "+Positive+ " Positive numbers!");
      System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
      System.out.println("You have have entered "+Negative+ " Negative numbers!");
      System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
    }
    catch (java.lang.NumberFormatException e)
    {
        System.out.println("Wrong format");
    }  

} 
}

Output if there are no errors

Enter '0' to quit.
Enter Numbers: 
1
5
5
-5
-5
0
You have have entered 5 numbers!
You have have entered 3 Positive numbers!
The Average of the Positive Numebers is 3.6666666666666665!
You have have entered 2 Negative numbers!
The Sum of the Negative numbers is -10!
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • You are amazing! There is only one problem left - if I enter double number, a letter or I just press enter the program should give me a Invalid format messsage... – Monster Dec 19 '14 at 16:16
  • Also if you enter: 1 5 5 you get 3 as average positive and it should be 3.66 – Monster Dec 19 '14 at 16:19
  • Try enter 1 5 5 -5 -5 and check the average – Monster Dec 19 '14 at 16:25
  • @Monster Have edited it again. Made a change while calculating average – Bhargav Rao Dec 19 '14 at 16:26
  • Thank you so much! It's perfect now! – Monster Dec 19 '14 at 16:31
  • I got curious if there is a way to save in a text file the System.out.printlns? – Monster Dec 19 '14 at 17:22
  • @Monster It is there, but you will have to ask it as a separate question as it is unrelated. Refer [this](http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/) and [this](http://stackoverflow.com/questions/2885173/java-how-to-create-and-write-to-a-file). They are good posts on writing into files. If you still have any doubts, then you can post a new question. All the best – Bhargav Rao Dec 19 '14 at 17:25
  • looks like I have reached my question limit and I cant ask new question, but here – Monster Dec 19 '14 at 17:30
  • @Monster You will have to wait for some time till you ask a new question. That is the rules of SO, I can't help – Bhargav Rao Dec 19 '14 at 17:32
1

check by parsing String to int

Integer.parseInt(str)>0  //positive number
Integer.parseInt(str)<0 //negative



do { 
      EnteredNumbers++;
      str = br.readLine();
      int number= Integer.parseInt(str);
      if(number>0){  //do positive stuffs}
      else if(number<0){//do negative stuffs}
    } while(!str.equals("0")); 
Bruce
  • 8,609
  • 8
  • 54
  • 83
  • I already tried to do that, but it seems I am messing something with the code because it keeps giving me errors... – Monster Dec 19 '14 at 16:11
1

Hope the below code achieves what you want to do

import java.io.*; 

class Nums { 
  public static void main(String args[])  
    throws IOException 
  { 
    BufferedReader br = new BufferedReader(new 
                            InputStreamReader(System.in)); 
    String str;
    int EnteredNumbers = -1;
    int Positive = 0;
    int Negative = 0;
    int NegativeSum = 0;
    double AveragePositive = 0;
    double PositiveSum = 0;

    System.out.println("Enter '0' to quit."); 
    System.out.println("Enter Numbers: "); 
    do { 
      EnteredNumbers++;
      str = br.readLine();
      if(Integer.parseInt(str) > 0){
          Positive++;
          PositiveSum = PositiveSum + Integer.parseInt(str);
          AveragePositive = PositiveSum/Positive;
      }
      if(Integer.parseInt(str) < 0){
          Negative++;
          NegativeSum = NegativeSum + Integer.parseInt(str);
      }

    } while(!str.equals("0")); 
      System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
      System.out.println("You have have entered "+Positive+ " Positive numbers!");
      System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
      System.out.println("You have have entered "+Negative+ " Negative numbers!");
      System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
  } 
}
Anakar
  • 112
  • 11
0

Create a list and keep adding the numbers into List. You should do something like:

List<Integer> numberList = new ArrayList<Integer>();

do { 
  str = br.readLine();
  int number = Integer.parseInt(str);
} while(number != 0); 

And then use for loop to do count like:

int negativeNumberSum = 0;
int positiveNumberSum = 0;
int positiveNumberCounts = 0;
for (int i =0; i<numberList.size(); i++) {
    if (numberList.get(i) >= 0) {
        positiveNumberSum += numberList.get(i);
        positiveNumberCounts ++;
    } else {
        negativeNumberSum += numberList.get(i);
    }
}

//print average of positive as positiveNumberSum /(double) positiveNumberCounts if positiveNumberCounts != 0
//print average of positive as negativeNumberSum / (double)(numberList.size() - positiveNumberCounts) same if (numberList.size() - positiveNumberCounts) != 0
//print positive count as positiveNumberSum  and same for negative.
//
SMA
  • 36,381
  • 8
  • 49
  • 73
0

Try using Integer.parseInt() to get an int from your string str, and checking to see if the integer is < 0 (negative) or > 0 (positive)

Tur1ng
  • 745
  • 8
  • 22
0

I have added an extra variable called PositiveSum to assist with the AveragePositive calculation.

In order to perform this calculation, you need to ensure the value is an Integer so I have added the parse statement.

class Nums { 
  public static void main(String args[])  
    throws IOException 
  { 
    BufferedReader br = new BufferedReader(new 
                        InputStreamReader(System.in)); 
    String str;
    int EnteredNumbers = -1;
    int Positive = 0;
    int Negative = 0;
    int NegativeSum = 0;
    int PositiveSum = 0; 
    double AveragePositive = 0;

    System.out.println("Enter '0' to quit."); 
    System.out.println("Enter Numbers: "); 
    do { 
      EnteredNumbers++;
      str = br.readLine();
      int number = Integer.parseInt(str);
      if(number<0) {
          Negative++;
          NegativeSum += number;
      } else if(number>0) {
          Positive++;
          PositiveSum += number;

      }

    } while(!str.equals("0"));
      AveragePositive = PositiveSum / EnteredNumbers;
      System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
      System.out.println("You have have entered "+Positive+ " Positive numbers!");
      System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
      System.out.println("You have have entered "+Negative+ " Negative numbers!");
      System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
  } 
}
James Fox
  • 691
  • 7
  • 24
0

Change your do-while loop: it is using Strings, not integers:

do { 
      EnteredNumbers++;
      num = sc.nextInt();

    } while(num != 0);

Also, you need to import the scanner utility:

import java.util.Scanner;

Don't use a BufferedReader, but use:

static Scanner sc = new Scanner(System.in);

Also, you would want to use a checker for your positive and negative numbers inside your do-while loop:

if(Integer.parseInt(num)<0) { Negative++; }
else { Positive++; }

I've also added a try-catch statement to handle an error if someone doesn't enter an int:

      try {
      num = sc.nextInt();
      }
      catch(Exception e) {System.out.println("Invalid integer"); System.exit(0); }

I added a little bit of code that takes the 0 off when it prints the numbers, as I realise it will include 0 when you type it in to exit. Change your class statement to public, it's just programming:

public class Nums {

Also, I add a negative-number counter in the main code, and an averager. Here is the complete code, to avoid confusion:

import java.io.*; 
import java.util.Scanner;
public class prime { 
  static Scanner sc = new Scanner(System.in);
  public static void main(String args[])  
  { 
    int EnteredNumbers = 0;
    int Positive = 0;
    int Negative = 0;
    int NegativeSum = 0;
    double AveragePositive = 0;
    int num = 0;
    int PosTotal = 0;
    System.out.println("Enter '0' to quit."); 
    System.out.println("Enter Numbers: "); 
    do { 
      try {
      num = sc.nextInt();
      }
      catch(Exception e) {System.out.println("Invalid integer!"); System.exit(0); }
      if(num<0) { Negative++; NegativeSum += num; }
      if(num>0){ Positive++; PosTotal += num; }
      EnteredNumbers++;
    } while(num != 0); 
      AveragePositive = PosTotal / Positive;
      EnteredNumbers -= 1;
      System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
      System.out.println("You have have entered "+Positive+ " Positive numbers!");
      System.out.println("The Average of the Positive Numbers is "+AveragePositive+ "!");
      System.out.println("You have have entered "+Negative+ " Negative numbers!");
      System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
  } 
}

Hope it helps! Note I have trial-tested it, and it works brilliantly. If you have any errors with this please tell me :)

Okx
  • 353
  • 3
  • 23