Solved

How to add array elements

Posted on 1997-06-27
13
257 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.
0
Comment
Question by:easy062697
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
13 Comments
 
LVL 6

Accepted Solution

by:
jpk041897 earned 100 total points
ID: 1222355
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
 

Author Comment

by:easy062697
ID: 1222356
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
 

Author Comment

by:easy062697
ID: 1222357
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:easy062697
ID: 1222358
Edited text of question
0
 

Author Comment

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


0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222360
> 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
 

Author Comment

by:easy062697
ID: 1222361
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
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222362
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
 

Author Comment

by:easy062697
ID: 1222363
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
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222364
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
 

Author Comment

by:easy062697
ID: 1222365
Adjusted points to 100
0
 

Author Comment

by:easy062697
ID: 1222366
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
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222367
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
login jsp example 24 104
eclipse buid path vs tomcat lib path 10 49
Delete Android all or certain applications data programmatically 9 149
using executorService 3 19
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question