How to add array elements

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.
easy062697Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jpk041897Commented:
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.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
easy062697Author 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.
0
easy062697Author 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.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

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


0
jpk041897Commented:
> 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.
0
easy062697Author 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.
0
jpk041897Commented:
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);
   }

}
0
easy062697Author 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!
0
jpk041897Commented:
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.
0
easy062697Author Commented:
Adjusted points to 100
0
easy062697Author 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.
0
jpk041897Commented:
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.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.