We help IT Professionals succeed at work.

How to add array elements

easy062697
easy062697 asked
on
Medium Priority
317 Views
Last Modified: 2010-04-16
Hi,
I have to read  data points(integers or float) from a file and display the result. I've written the following code and there is one compilation error.
import java.awt.*;
import java.io.*;
import java.lang.*;
public class surface extends java.applet.Applet{

//InputStream s= new FileInputStream("/home/megrad/akmancha/public_html/surface.data");
int[] foo = new int[500];
int x=0;
int i;
InputStream s;
      public boolean mouseDown(Event evt,int x,int y) {
      if(evt.target instanceof Button)
      try{
      InputStream s= new FileInputStream("/home/grad/xyz/abc/surface.data");
      }
      catch (IOException e) {
      System.out.println("IO Error: " + e.getMessage());
      }
      addit();
      return true;
      }

      public void addit(){
      s.read(foo);
      for(i=0;i < foo.length;i++) {
      if(foo[i]< 0)
      foo[i] = -foo[i];
      }
      x = foo[i]+x;
      display();
      }

      public void display() {
      TextField tf = new TextField("x",25);
      add(tf);
      }
}

I would like to know if my approach is correct,if not what is the correct way of doing it. Also what's the problem in this code(the error reads as:
surface.java:24: No method matching read(int[]) found in class java.io.InputStream.
        s.read(foo);
              ^
1 error

Thanks.
Comment
Watch Question

Try it as follows:

import java.awt.*;
import java.io.*;
import java.lang.*;
public class surface extends java.applet.Applet{

   DataInputStream s;
   int[] foo = new int[500];
   int x=0;
   int i;
   
   public boolean mouseDown(Event evt,int x,int y) {
      if(evt.target instanceof Button)
      try{
         s= new DataInputStream("/home/megrad/akmancha/public_html/surface.data");
      }
      catch (IOException e) {
         System.out.println("IO Error: " + e.getMessage());
      }
      addit();
      return true;
   }

   public void addit(){
      int is;
      i = 0;
      while ((is = s.readInt()) != null){
         foo[i] = abs(is);
         x += is;
         display();
      }
   }

   public void display() {
      TextField tf = new TextField("x",25);
      add(tf);
      Integer i = new (Integer(x));
      tf.setText(i.toString());
   }
}

Your approach was generaly correct, but you did make a few small mistakes.

First, both InputStream's and FileInputStream's read methods return byte arrays, you want to read int arrays so DataInputStream is better suited.

Second, There already exists ans absolute value method, abs(), no need for you to implement it.

Third, you were declaring s as local to mouseDown not local to the class, so it was out of context in addit().

Finaly, you were not displaying the result.

Since DataInputStream does not read in arrays of ints, I modified your code appropiatley.

I did not test the code, but it should be pretty close to working now.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Hi,
Thanks for your reply. I compiled the code and there was one error: surface.java:40: 'new(...)' not supported.
              Integer i = new (Integer(x));
                          ^
1 error
 I am unable to understand :

why you have created this "i".
What does the method "Integer" do?
In the "addit" method should it be x+=foo[i] instead of x+=is.
How to rectify the above error.
Is there any site where I can obtain a list of allthe methods and what they mean.


Thankyou.

Author

Commented:
Hi,
Thanks for your reply. I compiled the code and there was one error: surface.java:40: 'new(...)' not supported.
              Integer i = new (Integer(x));
                          ^
1 error
 I am unable to understand :

why you have created this "i".
What does the method "Integer" do?
In the "addit" method should it be x+=foo[i] instead of x+=is.
How to rectify the above error.
Is there any site where I can obtain a list of allthe methods and what they mean.


Thankyou.

Author

Commented:
Edited text of question

Author

Commented:
No.Ididn't edit the original question. I just wanted to correct a typo in my second mail!
 


> why you have created this "i".
To convert an int into a String.

>What does the method "Integer" do?
Integer is a wrapper class. It contains an int but adds a series of methods that allow you to operate on the int.

>In the "addit" method should it be x+=foo[i] instead of x+=is.
It could, but the line above asigns is to foo[i], and since a dirrect assinment is faster than an array assignment (due to internal pointer arithmetic) the way its written is more efficient (faster).

>How to rectify the above error.

Sorry about that error. Change the lines that read:

Integer i = new (Integer(x));
tf.setText(i.toString());

to

tf.setText(Integer.toString(x));

>Is there any site where I can obtain a list of allthe methods and what they mean.

Yes, you can download the Java Docs in WIndows Help format from:

http://www.dippybird.com

You can also get a copy of QUE's Java Quick reference for Java 1.02 (Windows Help version) when you download the Supercede IDE trial version from:

http://www.supercede.com

both tools contain all of the wrapper classes (and classes) in Java.

Author

Commented:
Hi,
I've done what you asked me to. But it still showed some errors.
So I've reduced my verbose code to a small size. The following is the result:
import java.awt.*;
import java.io.*;
import java.lang.*;
public class newsurface extends java.applet.Applet{

DataInputStream s;
Button b;
TextField tf;
int i=0,m;

      public void init() {
            b=new Button("Do it!");
          add(b);
          tf=new TextField(30);
          add(tf);
      }

      public boolean mouseDown(Event evt,int x,int y) {
         if (evt.target instanceof Button) {
            try{
                  s = new DataInputStream(new FileInputStream("/home/megrad/abc/def/xyz"));
                  while((m=s.readInt())!=0) {
                        i+=Math.abs(m);
                  }
                  tf.setText(Integer.toString(i));
               }

            catch(IOException e) {
                  System.out.println("IO Error :" + e.getMessage());
            }
        }
         return true;
      }
}
The above code does not show any errors at all. But the problem is it still doesn't show the result that I need. What baffles me is that neither the compiler nor does the applet show a "file doesn't exist" error even if I give a non-existent file for the DataInputStream.
I think the problem lies here,though I am not sure.

Please check my code and let me know the problem(Iwould appreciate if you could run it and see). You can give me a brand new code if that is more easy.But I would still like to see the problem here so that I donot repeat it again.

Thanks.
You are attemping to read a file from the client inside the applet. You also have on Init method. Try working with tis as a base:

import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;


public class newsurface extends Applet {
   
   

    Button b;
    textField tf;
    URL theURL;
    DataInputStream s;
    int i=0,m;
       
    void b_Clicked(Event event) {
       try{
         try{
            theURL = new URL("http://home/megrad/abc/def/xyz");
         } catch (MalformedURLException e){
            System.out.println("IO Error :" + e.getMessage());
         }
       
         s = new DataInputStream(new BufferedInputStream(             theURL.openStream()));

            while((m=s.readInt())!=0) {
               i+=Math.abs(m);
            }
            tf.setText(Integer.toString(i));
         }
         catch(IOException e) {
             System.out.println("IO Error :" + e.getMessage());
         }
       }


      public void init() {
           super.init();

           setLayout(null);
         addNotify();
         resize(426,266);
         b = new java.awt.Button("Do it!");
         b.reshape(120,156,154,38);
         b.setBackground(new Color(12632256));
         add(b);
         tf = new java.awt.TextField();
         tf.reshape(108,96,178,29);
         add(tf);
            
      }

      public boolean handleEvent(Event event) {
            if (event.target == b && event.id == Event.ACTION_EVENT) {
            b_Clicked(event);
            return true;
      }
      return super.handleEvent(event);
   }

}

Author

Commented:
Hi,

Thanks for your reply. I compiled your code without any problem. But I am getting the same problem again. The code is getting compiled without any error even if the file is non-existent. Nor am I getting the result if I give the correct file name. I have a file(to read the data from) and not an html document. So I am not sure if "URL" could be used. I have created a small sample file for this purpose which
consists of numerical numbers from 1 to 9(each on a separate line).

I think there is something fundamentally wrong. Please let me know if I am doing something wrong.

Thanks!
Well. to begin with, if the file contains:

1
2
3
4
...

as written here, you are writting strings, not integers. Integers are 2 byte values. If that is the case, you need to read strings, not integers, and then convert the strings to integers if you are doing operations on them.

Author

Commented:
Adjusted points to 100

Author

Commented:
Hi,
Then why don't I get an error when I compile the code. I don't want to change the code now. So I have to create an input file which has integers. Could you tell me how to do it(Any 5 data points would do).

Thanks.
Write a program with Basic, C or any other language that writes 5 integers.

In C :

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv){

file of = open("filename", "w");
for (i=1; i<=5; i++){
   _write(of, &i, 2);
}
close(of);
}

should do the trick.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.