Extremly needed java help!!!!!!!!!!

I am writing a program for my java class and I'm stuck on one part. In this program, I have to read integers from a file and put them into an ArrayList. Then I have to find the mean(average) of all the numbers ArrayList. I'm stuck on the part of adding the items of the ArrayList to an integer. Here is my code: **the part i'm having trouble with is in bold**


import java.lang.Integer;
import java.util.ArrayList;
public class onedarraylist
{
public static void main(String args[])
{
int w = 0, r = 0, c = 0;
EasyReader file = new EasyReader();
System.out.println("ENTER A FILENAME");
String f = file.readWord();
EasyReader console = new EasyReader(f);
while(!console.eof())
{
int num = console.readInt();
if(!console.eof())
{
w++;
}
}
console = new EasyReader(f);
ArrayList a = new ArrayList();
while(!console.eof())
{
int num = console.readInt();
Integer num2 = new Integer(num);
if(!console.eof())
{
c++;
a.add((c - 1), num2);
}
}
System.out.println("\n\nTHE MEAN OF THE ELEMENTS IN THE ARRAYLIST IS: ");
System.out.print(mean(a));
}
}
public static double mean(ArrayList a)
{
//precondition: arraylist a has at least one integer in it
//postcondition: returns the mean(average of the numbers in the ArrayList

int sum = 0;
for(int c = 0; c < a.size(); c++)
{
sum += a.get(c);
}
double avg = sum / a.size();
return avg;
}
}

If anyone could help me out, please reply back to this.
**NOTE:sorry about the spacing**

Comments

  • mondimondi Icrontian
    edited May 2006
    ArrayLists take Objects as their input, you must cast a.get(c) as an Integer.

    ie
    [PHP]
    sum += (Integer) a.get(c);
    [/PHP]

    also if you want to retain your formatting and make things look pretty and color coded you can encapsulate it in a PHP tag .. ie:

    [ PHP ] -> without the spaces
    blah blah blah
    [ /PHP ] ... again without the spaces..

    that way you dont have to do it manually :)

    hope that helps.

    M
  • edited May 2006
    thanx
  • edited May 2006
    i'm not sure what EasyReader is but i sure can't compile this stuff. what i can tell you is that you can't add an int and an Integer either, ints are primitive while Integers are objects. this is what you need:

    [PHP] public static double mean(ArrayList a)
    {

    //precondition: arraylist a has at least one integer in it
    //postcondition: returns the mean(average of the numbers in the ArrayList
    int sum = 0;
    for(int c = 0; c < a.size(); c++)
    {
    Integer fromList = (Integer)a.get(c);
    sum += fromList.intValue();

    }
    double avg = sum / a.size();
    return avg;

    }
    [/PHP]

    next, don't put the whole class in the main method. pull all that crap out and put it in another non-static method that gets called from inside main(). then mean() doesn't need to be static. you should limit static methods as much as possible, and your prof should have told you that. the class needs to look more like this:

    [PHP]
    import java.lang.Integer;
    import java.util.ArrayList;

    public class ArrayListMath
    {

    public static void main(String args[])
    {
    ArrayListMath test = new ArrayListMath();
    test.doWork();
    }

    public double mean(ArrayList a)
    {

    // precondition: arraylist a has at least one integer in it
    // postcondition: returns the mean(average of the numbers in the
    // ArrayList
    int sum = 0;
    for(int c = 0; c < a.size(); c++)
    {
    Integer fromList = (Integer)a.get(c);
    sum += fromList.intValue();

    }
    double avg = sum / a.size();
    return avg;

    }

    public void doWork(){
    int w = 0;
    int r = 0;
    int c = 0;
    EasyReader file = new EasyReader();
    System.out.println("ENTER A FILENAME");
    String f = file.readWord();
    EasyReader console = new EasyReader(f);
    while(!console.eof())
    {

    int num = console.readInt();
    if(!console.eof())
    {

    w++;

    }

    }
    console = new EasyReader(f);
    ArrayList a = new ArrayList();
    while(!console.eof())
    {

    int num = console.readInt();
    Integer num2 = new Integer(num);
    if(!console.eof())
    {

    c++;
    a.add((c - 1), num2);

    }

    }
    System.out.println("\n\nTHE MEAN OF THE ELEMENTS IN THE ARRAYLIST IS: ");
    System.out.print(mean(a));

    }

    }
    [/PHP]


    also note the name of the class follows convention with starting with an upper case letter and has some meaning.

    sorry to sound so picky but these are good coding conventions that you really ought to get into the habit of using now.


    --edit
    keep in mind this class probably wont even compile the way i've posted it. like i said, i dont have whatever library that EasyReader is part of. these are just suggestions. what i *am* sure about is the Integer/int part of mean().
  • edited June 2006
    EasyReader is a code written by the makers of my java textbook that reads objects and data structures. the code is:
    [PHP]// package com.skylit.io;
    import java.io.*;

    /**
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    *
    * Written as part of
    *
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    *
    * and
    *
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    *
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    *
    * <xmp>
    * Example:
    * =======
    *
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    *
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * {
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * }
    *
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    *
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    *
    * while (count < maxCount && !inFile.eof())
    * {
    * k = inFile.readInt();
    * if (!inFile.eof())
    * {
    * // process or store this number
    * count++;
    * }
    * }
    *
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    *
    */

    public class EasyReader
    {
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;

    /**
    * Constructor. Prepares console (System.in) for reading
    */
    public EasyReader()
    {
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    }

    /**
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    */
    public EasyReader(String fileName)
    {
    myFileName = fileName;
    myErrorFlags = 0;
    try
    {
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    }
    catch (FileNotFoundException e)
    {
    myErrorFlags |= OPENERROR;
    myFileName = null;
    }
    }

    /**
    * Closes the file
    */
    public void close()
    {
    if (myFileName == null)
    return;
    try
    {
    myInFile.close();
    }
    catch (IOException e)
    {
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    }
    }

    /**
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    */
    public boolean bad()
    {
    return myErrorFlags != 0;
    }

    /**
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    */
    public boolean eof()
    {
    return (myErrorFlags & EOF) != 0;
    }

    private boolean ready() throws IOException
    {
    return myFileName == null || myInFile.ready();
    }

    /**
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    */
    public char readChar()
    {
    char ch = '\u0000';

    try
    {
    if (ready())
    {
    ch = (char)myInFile.read();
    }
    }
    catch (IOException e)
    {
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    }

    if (ch == '\u0000')
    myErrorFlags |= EOF;

    return ch;
    }

    /**
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    */
    public String readLine()
    {
    String s = null;

    try
    {
    s = myInFile.readLine();
    }
    catch (IOException e)
    {
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    }

    if (s == null)
    myErrorFlags |= EOF;
    return s;
    }

    /**
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    */
    public String readWord()
    {
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;

    try
    {
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    {
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    };

    if (count > 0)
    {
    myInFile.reset();
    s = buffer.toString();
    }
    else
    {
    myErrorFlags |= EOF;
    }
    }

    catch (IOException e)
    {
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    }

    return s;
    }

    /**
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    */
    public int readInt()
    {
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    }

    /**
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    */
    public double readDouble()
    {
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    }
    }

    [/PHP]

    And I ended up fixing my code and adding some methods(thanx to mondi). It is:
    [PHP]/*Fabs
    onedarraylist*/
    import java.lang.Integer;
    import java.util.ArrayList;
    public class onedarraylist
    { public static void main(String args[])
    { int w = 0, r = 0, c = 0;
    EasyReader file = new EasyReader();
    System.out.println("ENTER A FILENAME");
    String f = file.readWord();
    EasyReader console = new EasyReader(f);
    while(!console.eof())
    { int num = console.readInt();
    if(!console.eof())
    { w++;
    }
    }
    console = new EasyReader(f);
    ArrayList a = new ArrayList();
    while(!console.eof())
    { int num = console.readInt();
    Integer num2 = new Integer(num);
    if(!console.eof())
    { c++;
    a.add((c - 1), num2);
    }
    }
    System.out.println("THE NUMBER OF ITEMS IN THE ARRAYLIST IS: ");
    System.out.print(numItems(a));
    System.out.println("\n\nTHE MEAN OF THE ELEMENTS IN THE ARRAYLIST IS: ");
    System.out.print(mean(a));
    System.out.println("\n\nTHE MAXIMUM NUMBER IN THE ARRAYLIST IS: ");
    System.out.print(max(a));
    System.out.println("\n\nTHE MINIMUM NUMBER IN THE ARRAYLIST IS: ");
    System.out.print(min(a));
    System.out.println("\n\nTHE NUMBER EVEN NUMBERS IN THE ARRAYLIST ARE: ");
    System.out.println(evenNums(a));
    }
    public static int numItems(ArrayList a)
    { //post: returns the length of the arraylist
    int len = a.size();
    return len;
    }
    public static double mean(ArrayList a)
    { //pre: The arraylist a has at least one integer in it
    //post: returns the mean(average) of the numbers in the arraylist
    double sum = 0;
    for(int c = 0; c < a.size(); c++)
    { sum += ((Integer)a.get(c)).intValue();
    }
    double avg = sum / a.size();
    return avg;
    }
    public static int max(ArrayList a)
    { //pre: The arraylist a has two or more integers in it
    //post: returns the maximun value in the arraylist
    int max = ((Integer)a.get(0)).intValue();
    for (int c = 1; c < a.size(); c++)
    { if (((Integer)a.get(c)).intValue() > max)
    { max = ((Integer)a.get(c)).intValue();
    }
    }
    return max;
    }
    public static int min(ArrayList a)
    { //pre: The arraylist a has two or more integers in it
    //post: returns the minimun value in the arraylist
    int min = ((Integer)a.get(0)).intValue();
    for (int c = 1; c < a.size(); c++)
    { if (((Integer)a.get(c)).intValue() < min)
    { min = ((Integer)a.get(c)).intValue();
    }
    }
    return min;
    }
    public static String evenNums(ArrayList a)
    { //post: returns the number of even numbers in the arraylist
    String q = "";
    int w = 0;
    for(int c = 0; c < a.size(); c++)
    { if(((Integer)a.get(c)).intValue() % 2 == 0)
    { w++;
    }
    }
    q += w;
    return q;
    }
    }[/PHP]
  • edited June 2006
    i'm glad you got your stuff working.

    not to harp more but if you do continue java programming, once you get into higher classes you'd likely get raked over the coals for that program, regardless if it produces the proper output. from a design standpoint, static classes and functions take away the 'object oriented' aspect of java.

    you've seen the keyword 'this' reference a private member variable right?

    [PHP]

    public class MyClass{

    private String myName = "";

    .
    .
    .
    public void setName(String name){
    this.myName = name;
    }
    .
    .
    }//end myClass

    [/PHP]


    from a technical standpoint, static functions/variables aren't bound to any particular instance of an object, taking away the ability to reference that static function/variable with the 'this' keyword in that class. and since there's no 'this', we get that error about how static member functions can't call nonstatic method functions.

    let's switch up my earlier example:

    [PHP]
    public class MyClass{

    private static String myName = "";

    .
    .
    .
    public void setName(String name){
    //this.myName = name; //can't do this, compiler throws an error because myName doesn't belong to the instance, it belongs to the class. instead, do this:
    MyClass.myName = name;
    }
    .
    .
    }//end myClass

    [/PHP]

    as a good rule of thumb: in the case where neither class nor instance variables are accessed, one should determine if the method "operates" on the class or the instance. if it operates on the class (like all the Math functions, they operate on objects of various types), then make it static, else make it non-static. none of your methods really *need* to be static, as they operate on the instance.

    another point, static functions can't be extended. if you have to extend a class and override a method, you won't be able to if that method is static. non-static funtions add more flexibility to the code...

    this stuff may not seem applicable to you now, but if you continue programming in any OO language, it's crucial to 1) form good coding habits early and 2) try to understand object oriented concepts such as objects, object types, encapsulation, polymorphism, variable scope(actually variable scope knowledge is applicable to all languages, OO or not) and variable/method access.


    the commonly used example i'm trying to drive home goes like this :

    [PHP]
    public class StaticDemo {

    public String my_member_variable = "somedata";

    public static void main (String args[]) {
    // Access a non-static member from static method
    System.out.println ("This generates a compiler error " + my_member_variable );
    }
    }
    [/PHP]

    [PHP]
    public class NonStaticDemo {

    public String my_member_variable = "somedata";

    public static void main (String args[]) {
    NonStaticDemo demo = new NonStaticDemo();

    // Access member variable of demo
    System.out.println ("This WON'T generate an error " + demo.my_member_variable );
    }
    }
    [/PHP]

    hope this helps.....

    i'd recommend a great book by Joshua Bloch called "Effective Java". he goes over some of the finer aspects of java programming and touches on a lot of these topics in real world scenarios.
Sign In or Register to comment.