my code should accept 5 numbers, sum them up , average them.. and print the numbers that are below the average


it doesnt appear to be working..why?

import java.io.*;


class Pra1
{
     public static void main(String[] args)
     {
     Console console=System.console();
     int size=5;
     int number=0;
     String allNumbers="";
     String Snumber="";
     int sum=0;
     int avg=0;
     int index=0;
     int num=0;
 
         for(int i=0;i<size;i++)
         {
         System.out.println("enter a number");
         number=Integer.parseInt(console.readLine());
         
         sum+=number; 
         allNumbers+=number+",";
         }
     
         avg=sum/size;
         System.out.println("your average is "+avg);
   
         while(index<allNumbers.length())
         {
                while(allNumbers.charAt(index)!=',')
                {
                  Snumber+=allNumbers.charAt(index);
                  index++;
                } 
                num=Integer.parseInt(Snumber); 
                if(num<avg)
                System.out.println(Snumber);
         index++;
         }
    }
}

java.io
Class Console
is wonderful since it lets you to access the character-based console device, if any, associated with the current Java virtual machine.
Console console=System.console();
However, the
java.util
Class Scanner
is also goog since it may carry the same job.
Scanner in = new Scanner(System.in);
I have two comments.
1. to use methods as much as possible.
2. We should define the number as double since number could be in int, float, or double. And parseDouble accepts int as double
Please test the following code to see if there is any error.

import java.io.*;
class Input {
	
	static double average(double d[]){ // the static method returns the mean value of the double array
		double sum=0.0; // the place to store the totting-up values. It was zero at very beginning
		for (int i=0; i<d.length; i++) // the loop to sum up the elements of the array d
			sum += d[i];
		return sum/d.length; // returns the average value
	}
     public static void main(String[] args) {
     Console console=System.console(); // establish an input channel
     int size=5; // input 5 numbers altogether
     double number[]=new double[size]; // define a double array to store the 5 numbers
         
     System.out.println("enter 5 numbers");  
     for(int i=0;i<size;i++)
     number[i]=Double.parseDouble(console.readLine()); // input number could be in the format of int or double
     double ave = average(number); // call the average method to obtain the mean value of the array number
     
     System.out.println("The numbers smaller than the mean are printed as follows");
     for (int i=0; i<size;i++) // the for loop scanning the array.
     if (number[i]<ave) // if the element is smaller than the average
     System.out.printf("%7.2f ", number[i]); // print the value
     System.out.printf("\nThe average is %7.2f\n", ave);  // print the mean value     
    }
}

Edited 6 Years Ago by tong1: put a Title

oooh..

i just asked to see where was the little mistake that i made in my code

So, NewOrder - what was the problem you were running into? I see a few potential trouble spots, but I'd like to know what question you're asking before I go answering it. :)

NewOrder, your idea is good. You have almostly done.
The problem is found in the line 12:

String Snumber="";

When you at the first time come into the nested while loop:

while(allNumbers.charAt(index)!=',')

it works fine. However, when you use the Snumber at the second time, Snumber holds the previous result that should be removed. In fact, the Snumber finally holds your all ditigs after removing all the comma sign ','.
Solution:
Move String Snumber=""; at line 12 by inserting it after line 31
so that each time shortly after outerloop :

while(index<allNumbers.length())

starts you are able to restart the Snumber, that is, make a new Snumber by the decraration: String Snumber=""

Edited 6 Years Ago by tong1: n/a

sorry for the post above, tong1 solved the problem!!


thanks tong1. i had that problem when i defined string variables ="". the program refered to the "" and not to the data collected.

why does that error occur? should i let some of my string varibles die inside the loop to prevent that mistake/

tong1, can you explain in detail what is happening when i put String Snumber=""; inside the loop. why does it work?

Edited 6 Years Ago by NewOrder: n/a

Dear NewOrder, jon's post is very important which tells you how to ask question precisely. Please read the web site jon indicates.
I explain how String Snumber="" works.
Each time when you declare String Snumber=""; you will have a new instance of String with no character. Then for example, after executing Snumber += "a"; the Snumber instance will change location to store "a". You should know the Sting instance is a constant which can not become larger like StringBuffer. If you want Snumber to have a 'a', you have to find a new location for Snumber. The String instances may work well with '+=' while StringBuffer instances shoud work with its method append(String s). You have placed the String Snumber =""; into the outerloop so that it becomes the fist line of the loop body. So each time when starting a new loop, a new instance of Snumber is created so that it will get ride of previous contents and store the next digit's string. Snumber changes location after each execution of '+=".
jon, am I right.
P.S. If you want to let some object, such as an instance of String Snumber, dead, you may use the code:
Snumber=null;
so that the garbage collector will return the Snumber to operation system.

Edited 6 Years Ago by tong1: n/a

The += operator is defined for String, but not for StringBuffer. For String, it gives you the same result as the equivalent = and plus statements:

if you have
String string = "foo", n = "bar";

then

string = string + n;
and
string +=n;

are equivalent. Both of these concatenate the two strings, assign the result into a new String, and store a reference to that new String object in the variable string. So if you want to be precise the object to which Snumber is pointing changes location with each iteration. Snumber is a local reference to some String which lives on the heap. Snumber lives on the stack, and points to some String. Where it points changes each time you assign it. (With a StringBuffer, the variable's reference remains constant, and the object it points to changes).

I'm pretty sure all of that's right, but it's early in the morning and I may have fat-fingered something, mentally speaking.

I'm not seeing the relation between this last post and the code at the top of the thread - was there some other code in there? Maybe I'll see it when I get into work and have some coffee.

As for killing an object, yes, if you remove the last reference to an object, the garbage collector will eventually come along and retrieve that stack space. This is not guaranteed to happen immediately, but in most programs I can guarantee that you won't notice or care when it happens. Garbage collection (memory management) is not something you're ever going to have to think about much, as far as I can tell. This is one of the best things about programming in java, as you'll find if you stick your nose into C for more than a few minutes.

jon and tong1 thank you for the explanation. now it is all crystal clear to me.

i would regard this thread as solved!!

This question has already been answered. Start a new discussion instead.