Writing a Class

Hi, can anyone help me out with this, this is what I need to do:
Write a Java class that represents a 2-dimensional array. It should include the following:
? class variables to represent the number of rows and columns
? a constructor that creates an N X N matrix
? a constructor with two parameters of type double specifying number of rows and columns
? three accessor methods that return 1) the number of rows, 2) the number of columns and 3) the total number of elements in the array
? a toString method that overrides the Object method with the same name, and returns a String representing the array in the following format:
[nrow: 10, ncol: 10] for a 10 X 10 array
Now i'm still very new to Java and i'm confused about a lot of this.
I have only written the 2 constructors so far:
public class array {
     public array(int N) {
          int[][] newarray = new int[N][N];
     public array(double rows, double columns) {
          double[][] newarray = new double[(int) rows][(int) columns];
}I'm not even sure if those are right.. Also, for "class variables to represent the number of rows and columns", I tried doing this for the variables rows and columns, but the compiler complained whenever I used them in the constructors.
Can anyone help me as to how to write the accessor methods and the toString method as well?
Thank you.

I was in a great trouble because of mine huge extra pounds. In society, in office every where I faced a bulk of problems . I tried to get rid of it and couldn't get success while spoil a big part of my funds on various programs. Then my friend told me about Acai Berry and I got surprising outcome . Can you believe that I lost my 30 pounds in a month and now I am happly in my life.So I suggest you to visit
[How I Lost 30 Pounds in Under 30 Days Using The Acai Berry|http://ezinearticles.com/?Acai-Berry---How-I-Lost-30-Pounds-in-Under-30-Days-Using-The-Acai-Berry&id=1998407]
Edited by: rsheal on Feb 23, 2009 10:37 PM

Similar Messages

  • Please help with writing a class

    i need help getting started with this assignment. i haven't done anything with writing classes, so i don't know where to start.
    i need to create a bank account class that will keep a name, balance, up to 50 deposits, and up to 50 withdrawls. i need to include 2 arrays for the deposits and withdrawls.
    Here's what i know:
    I need a constructor that takes zero arguments. This constructor would initialize the numeric value to zero.
    I need a 2nd constructor that takes one argument, a name as a String value. This constructor would initialize the numeric value to zero.
    I need a 3rd constructor that takes two arguments, a name as a String value and a starting "balance" as a double value

    Sorry, I was watching a movie with my wife ...imagine that. Study my examples here and try to understand what I have done. You will follow the same methodology for the rest of the program. Use main to test the methods in your program.
    public class mdlAccount {
      String name;
      double balance;
      int currentDeposit = 0;
      int currentWithdrawl = 0;
      double[] deposits = new double[50];
      double[] withdrawals = new double[50];
      public mdlAccount() {
        name = "";
        balance = 0.0;
      public mdlAccount(String name) {
        this.name = name;
        balance = 0.0;
      public mdlAccount(String name, double balance) {
        this.name = name;
        this.balance = balance;
      // When the instructor says: Have a method that does deposits...
      // You need to create a method, similar to the constructors,
      // but with a return value, even if it returns void (nothing).
      // Like this:
      public void deposit( double amount ) {
        // Do some error checking.
        if ( currentDeposit < 50 && amount > 0 ) { // > is a greater than sign
          // If all is ok, add to the balance...
          balance += amount;
          // and add the entry to the array of deposits
          deposits[currentDeposit] = amount;
          // Finally, add 1 to the currentDeposit variable.
          currentDeposit++;
      // We need the 'return the balance' method so we can see if
      // the program runs correctly. This time we return a double,
      // instead of void. (void means don't return anything at all).
      public double getBalance() {
        return balance;
    // Now you create the next method for withdrawals...
    //  if ( currentWithdrawl < 50 ) {
    //    deposits[currentWithdrawl] = amount;
    //    currentWithdrawl++;
      // You want a main method so this class can be executed.
      // You can remove it later if you want to use this class
      // from within another larger program.
      public static void main(String[] args) {
        mdlAccount acct = new mdlAccount( "GumB", 100.0 );
        System.out.println("Initial balance is " + acct.getBalance());
        acct.deposit( 50.0 );
        System.out.println("Current balance is " + acct.getBalance());

  • Reading & writing binaries(.class files)

    folks,
    how does one go about reading and writing .class files in java. I am able to write 'em only in ASCII format which is not what i want.
    Thanks!

    Did anybody say anything about disassembling?He wants to read and write class files, it's the title of the post.
    I don't appreciate you dismissing my suggestions like that.
    There's plenty of gotchas in reading and writing class files, such as Longs & Doubles taking up 2 positions in the constant pool.
    Hence the reason why I suggested using an open source library like BCEL or ASM. These are still valid as class readers, even if you don't touch the byte code. ( disassembly )
    But what would I know Ejp....sure I only wrote my own Java 1.5 class reader / disassembler.

  • How to get the ServletContext when writing a class

    Morning,
    I've got a project using al least 4 jsp documents that try to manipulate a mysql database
    To access the database and get a connection, i've put this syntax at the start of each document
    <%! Connection con; %>
    <%     
    String url =  (String)application.getInitParameter("databaseUrl");
                   String username = application.getInitParameter("username");
                   String password = application.getInitParameter("password");
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
               con = DriverManager.getConnection(url, username, password);
                   %>Those documents also use classes that I create, what I want to do is keep the code I've written above in one place instead of 4 different places, Is there a way I can use the application variable, which belongs to ServletContext in a class (not a servlet)
    Message was edited by:
    Octavian

    This syntax reference JSP 2.0 : http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html
    covers JSP actions such as jsp:useBean , jsp:getProperty and jsp:setProperty.
    The API for JSTL is pretty intuitive:
    http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
    But if you need more details on a particular JSTL tag you can refer to the JSTL 1.1 Specification - it's a PDF document.
    JSTL also uses EL (Expression Language) which is also covered by the JSTL specification and by the above JSP 2.0 syntax reference.
    There are many JSTL tutorials and articles too, but most of them are old so they contain JSTL 1.0 code.
    To get yourself started you need jstl.jar and standard.jar which come with the latest JSTL 1.1 distribution found here:
    http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html
    Standard-1.1 (JSTL 1.1) requires a JSP container that supports the Java Servlet 2.4 and JavaServer Pages 2.0 specifications. Jakarta Tomcat 5 supports the new specifications. The Standard-1.1 taglib has been tested with Tomcat 5.0.3.
    After you have set up your environment you can test it with a small sample of JSTL code like this:
    inside sample.jsp
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:set var="someVariable" value="Hello World!"/>
    <c:out value="${someVariable}/>
    null

  • Writing a class to provide Self ID capability in a JAR file.

    Hello,
    I need to write a class which reads and prints out the contents of the manifest file of the JAR file of which it is a part. I've got the code for reading the manifest file, which I've included below.
    My question is this: how can I get this class to find out the name of the JAR file it's in so I don't have to hard code "myJar.jar" as I have below?
    Thanks.
    import java.util.*;
    import java.util.jar.*;
    import java.io.*;
    public class SelfID {
    public static void main(String[] args) throws IOException {
         System.out.println("The manifest for this jar file:");
         //Create JarFile reference
         JarFile jarFile = new JarFile("myJar.jar"); //I don't want Jar File name hard coded
         //Create Manifest reference
         Manifest manifest = jarFile.getManifest();
         System.out.println(manifest.toString());
         //Create Map of manifest key/value entries
         Map entryMap = null;
         entryMap = manifest.getMainAttributes();
         //Display contents of manifest file
         Iterator it = entryMap.keySet().iterator();
    while( it.hasNext() ) {
    Attributes.Name key = (Attributes.Name)it.next();
    String value = (String)entryMap.get(key);
    System.out.println(key.toString() + " = " + value);
    }

    In case anyone is wondering what self ID information in the manifest I am talking about--the custom ID information I am going to put there. I don't want to have to go back and modify the source code any time the name of the JAR file must change, which could one day become a requirement.

  • Flex with any ORM - Writing Model classes and action scripts redundant?

    Hi,
    I am using Hibernate with Flex. I have all my model classes
    as POJOs. Now if i have to access these POJOs directly from flex, I
    need to write action script reference classes for all my POJO model
    classes. Since mapping POJOs with action script reference classes
    is so mechanical, i am wondering if there is any tool to read all
    the properties from the POJO's and convert them to action script
    reference classes automatically. Is there any way that this can be
    automated?
    Thanks in advance.
    Chandu.

    If you use Granite Data Services, there's something called
    "gas3" (I think is the name). You may be able to use it even if you
    don't use Granite.
    I didn't care for learning how to use it (plus it uses
    Groovy, more needless stuff to learn I guess), so I can't say how
    well it works. I just wanted a simple custom ant task that
    generates ActionScript classes for my Java classes. So I ended up
    making my own. It's definitely not trivial but it's not that hard
    if you're very good with Java and reflection.

  • Writing a class using random generator in bluej

    Hello
    Im trying to write a class for a deck of cards. Im using a random generator but I dont know how to write the instance variable.
    I have to make 4 suits heart, club, spade, dimonds. and 13 for face value. I know how to random generate numbers. Like if I were making a slot machine to give me 3 numbers in a rage from 0-10. Thats just numbers. How do I random generate values of 1-13 and have it output a random suit? Also how do I make it say if its a jack king or queen? Do I need a constructor or how would I make the card with the face value of 13 suit heart and the card be a queen.
    before jumping down my throat about this being a homework assignment...yes it is but this step Im seeking help on there is no example for this type of generating.
    Thanks for any help
    Rewind

    Well, this is far from bullet-proof, but I think gets the basic idea across. This does sampling with replacement; if you wanted to do something like shuffle a deck of cards you'll need a smarter approach than this.
    import java.util.*;
    public class RandomCards {
      public static void main(String[] args) {
        Suit suit=new Suit();
        for (int i=0; i < 10; i++) {
          System.out.println(suit.nextSuit());
      private static class Suit {
        public static final String HEART="Heart";
        public static final String DIAMOND="Diamond";
        public static final String SPADE="Spade";
        public static final String CLUB="Club";
        private final String[] SUITS={ HEART, DIAMOND, SPADE, CLUB };
        private Gen suitGen=new Gen(0,3);
        public String nextSuit() {
          return SUITS[suitGen.nextInt()];
      private static class Gen {
        private int floor,ceiling;
        private Random rand;
        public Gen(int floor, int ceiling) {
          this.floor=floor;
          this.ceiling=ceiling;
          rand=new Random();
        public int nextInt() {
          return rand.nextInt(ceiling-floor)+floor;

  • Writing a class to open jDialog that can be used over and over

    Hi All
    I am hoping that some out there can help me with this.
    I have a lot of Dialogs that I what to open and close.
    I am using the code to do that , and it works fine.
    What i would like to do is write a class that I can call and just pass in the name of the dialog that I what to open.
    Something like this
    private String dialogeName;
    dialogeName = Contacts;
    So from another class using a button I could do this type of call
    some way of passing into this class the Dialog name. I don't know how to do that ether .
    Is there some way of getting to this private String dialogeName; from another class ??
    Is this posable ??
    PLEASE SOMEONE HELP ME .....................
        Contacts dlg = new Contacts();   // Works fine  but to have to call the same code over and over
       // is a pain and the only difference is the name of the dialog.
        dialogeName = Contacts;  // this is what I would like to be able to do
       // dialogeName dlg = new dialogeName();
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = getSize();
        Point loc = getLocation();
        dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x,
                        (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setModal(true);
        dlg.pack();
        dlg.show();Thanks to all that have taken the time to look and to help
    Craig

    Why not simply create a method that wraps all the redundant stuff?
    public JDialog showDialog(JDialog dlg)
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = dlg.getSize();
        Point loc = dlg.getLocation();
        dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x,
                        (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setModal(true);
        dlg.pack();
        dlg.show();
        return dlg;
    }Then you could call it with all your various dialog types:
    Contacts dlg = (Contacts)showDialog(new Contacts());
    OtherDialog dlg2 = (OtherDialog)showDialog(new OtherDialog());Of course in this example Contacts and OtherDialog classes must extend JDialog.

  • Help writing a class

    Trying to learn how to write a class. I had this AS for a
    video player that was working in my file and I am trying to learn
    how to move code like it into a class.
    I am doing what I think I need to, but am getting a bunch of
    errors that I don't know what to do with.
    My class starts like this and I am getting the following
    error:
    import mx.utils.Delegate;
    class VideoPlayer extends MovieClip{
    private var nc:NetConnection = new NetConnection();
    nc.connect(null);
    The nc.connect(null); part is giving me the following error
    message:
    "This statement is not permitted in a class definition."
    Why is that and how do I get around that?
    Thank you very much for any help!

    Ah, I get it. Sorry totally new to classes and having some
    issues with them...
    Thank you!!!

  • Writing a class "manual" in Pages ?

    I have Pages 2 and as part of this semester at College I will have to write a "manual" which is to be around 40 or so pages long.
    The manual must have screen shots with subtitles, bibliography, index and so forth. Unfortunately the entire class will be preparing their manuals with Word. I'd like to use Pages, but may have to provide a Word compatible copy.
    Has anyone done something like this and successfully exported it to Word format?
    I'm hoping I can get away with providing pdf format

    I don't think anyone can tell you how well Pages exports to Word. It depends entirely on the document. I'm into simple documents and I usually get the export good enough. Other people in this forum have occasionally screamed loudly about how bad the export is.
    If you want a less than trivial Word document as final output, and the result is really important, and you don't have the time or possibility to experiment yourself, I would suggest you use another tool than Pages. I've heard that MS Word is fairly good at creating Word documents.

  • Writing main class (All in one method or split into several?)

    Hello,
    How is the common practice to write a main method?
    I use to write one method if nothing repeats it self then I make a private method for it.
    Like this
    public static void main(String[] args) {
    foo();
    foo();
    private void foo(){
    }But I have read a lot of main methods where there is private methods which is only executed ones.
    And the main method calls a new private method like this
    public static void main(String[] args) {
    foo(args);
    private void foo(String[] args){
    foo2();
    foo3();
    foo4()
    private void foo2(){
    private void foo3(){
    private void foo4(){
    }

    I think its better to do the second example
    but it does not really make a difference
    Example 1 you have to say xyzClass.foo();
    Example 2 you call the methods directly
    public class XYZ{
      public XYZ(){
      public void method1(String s){ 
      public void method2(){ 
      public void method3(String s){ 
      public void method4(String s){
      public void method5(String s){ 
      public method(String[] args){
        method1(args[0]);
        method2(args[1]);
        method3(args[2]);
        method4(args[3]);
        method5(args[4]);
      }main methods
    public static void main(String[] args){
      XYZ xyz = new XYZ();
      xyz.method1(args[0]);
      xyz.method2(args[1]);
      xyz.method3(args[2]);
      xyz.method4(args[3]);
      xyz.method5(args[4]);
    //vs.
    public static void main(String[] args){
      XYZ xyz = new XYZ();
      xyz.method(args);
    }Edited by: gtRpr on 2008/07/22 01:42

  • Writing a Class for making the 'enemies' follow the 'player'...

    Greetings;
    I'm an actionscript beginner and trying  to write a class to  make the 'enemies' follow the 'player' (shown below). I'm trying to write it such that it takes two MovieClips as arguments, and moves the first one toward the second one. When I import the Class try to use it in Main.as by typing  " var followPlayer:FollowPlayer = new FollowPlayer(fishMov0, player);", I get the following error:
    "ArgumentError: Error #1063: Argument count mismatch on jab.enemy::FollowPlayer/followPlayer(). Expected 2, got 1."
    Any ideas/suggestions would be appreciated.
    Thanks,
    Jeremy
    package  jab.enemy
        import flash.display.MovieClip;
        import flash.events.Event;
        public class FollowPlayer
            private var _clip1:MovieClip
            private var _clip2:MovieClip
            private var speed:uint = 1.5;
            public function FollowPlayer(clip1:MovieClip, clip2:MovieClip): void
            // clip1 is the enemy, clip2 the player being followed.
                _clip1 = clip1;
                _clip2 = clip2;
                _clip1.stage.addEventListener(Event.ENTER_FRAME, followPlayer);
                _clip2.stage.addEventListener(Event.ENTER_FRAME, followPlayer);
            private function followPlayer(_clip1:MovieClip, _clip2:MovieClip)
                    if (_clip1.y > _clip2.y)
                        _clip1.y -= speed;
                    if (_clip1.y < _clip2.y)
                        _clip1.y += speed;
                    if (_clip1.x > _clip2.x)
                        _clip1.x -= speed;
                    if (_clip1.x > _clip2.x)
                        _clip1.x -= speed;

    Thanks guys! My code was seriously flawed, but I ended up getting it to work. For anyone else that might be interested, see 'FollowPlayer' below, an extremely simple class which takes two MovieClips as arguments, and moves the first one slowly (at 24fps) toward the second one:
    package  jab.enemy
        import flash.display.MovieClip;
        import flash.events.Event;
        public class FollowPlayer
            private var _clip1:MovieClip
            private var _clip2:MovieClip
            private var speed = 1 + Math.random();
            public function FollowPlayer(clip1:MovieClip, clip2:MovieClip): void
            // clip1 is the enemy, clip2 the player being followed.
                _clip1 = clip1;
                _clip2 = clip2;
                _clip1.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame)
                function onEnterFrame(event:Event):void
                    if (_clip1.y > _clip2.y)
                        _clip1.y -= speed;
                    if (_clip1.y < _clip2.y)
                        _clip1.y += speed;
                    if (_clip1.x > _clip2.x)
                        _clip1.x -= speed;
                    if (_clip1.x < _clip2.x)
                        _clip1.x += speed;

  • Weblogic Class Loader caching/writing classes to weblogic/myServer/classfiles

    It seems that if I compile a class that a JSP uses while Weblogic is
              running, Weblogic's class loader has this nasty habit of caching/writing
              the class that already has loaded into memory into:
              weblogic/myServer/classfiles
              Weblogic then refers to the older class file under the above directory
              when the server is started again. Is there any way to turn this "class
              loader caching" off in Weblogic? Thanks!
              -hjk
              

    You have to tell WLAS where to load your new classes. You can change
              workingDir of your JSP configuration in weblogic.properties to point to your
              new class directory.
              Cheers - Wei
              Hyung-Jin Kim <[email protected]> wrote in message
              news:[email protected]..
              > It seems that if I compile a class that a JSP uses while Weblogic is
              > running, Weblogic's class loader has this nasty habit of caching/writing
              > the class that already has loaded into memory into:
              >
              > weblogic/myServer/classfiles
              >
              > Weblogic then refers to the older class file under the above directory
              > when the server is started again. Is there any way to turn this "class
              > loader caching" off in Weblogic? Thanks!
              >
              > -hjk
              >
              

  • Problem with variable in class file.

    Im working on a project from school where I read in a text file with numbers and print the max and the min. In my main file, I read in the text file and set the different numbers to variables a, b, and c. My question is, when Im writing my class file MaxMin, is there anyway to access those variables to compare them? Or will I have to do it some other way. Thanks for your help.

    Ok. Sorry
    Here is the main code
    import java.io.*;
    import java.util.StringTokenizer;
    public class LabAssign1
    public static void main(String[] args) throws IOException
    final int TOKENS_PER_LINE = 3;
    String fileName = "labassign1.txt";
    File theFile = new File(fileName);
    FileInputStream theStream = new FileInputStream(theFile);
    InputStreamReader theReader = new InputStreamReader(theStream);
    BufferedReader input = new BufferedReader(theReader);
    int numLines = 0;
    String line = input.readLine();
    while (line != null)
    StringTokenizer st = new StringTokenizer(line);
    if (line.length() == 3)
    int a = Integer.parseInt(st.nextToken());
    int b = Integer.parseInt(st.nextToken());
    int c = Integer.parseInt(st.nextToken());
    else
    line = input.readLine();
    input.close();
    Is there any way to call variables a,b,and c in a separate class file?

  • Reading and Writing to a Log file

    Hello,
    I'm writing a class that will write a user id to a log file every time they click on a particular button. However, I don't want a new line every time a user clicks on the button, I'd like to be able to find their id in the log, increment a counter and write that back to the log in place of the previous entry.
    For example, User A clicks on the button for the first time so I write in the log:
    User A 1
    Next time they come along, I want to see if User A exists in the log - which they do - add 1 to the counter and replace User A 1 with User A 2. So the log will now say:
    User A 2
    I was thinking of writing to the log, reading the log back in to a HashMap and then writing the HashMap out every time. Seems like a rather inefficient solution. Is there anything else I can do?
    Thanks!

    Hi,
    counters are a standard topic. Many solutions are to be found in
    textbooks. Here is one of them (Hunter & Crawford Java Servlet
    Programming):
    String activeUser = ... ;
    try
      FileReader fileReader = new FileReader( "mylog" );
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      FileWriter fileWriter = new FileWriter("mylog.new");
      BufferedWriter bufferedWriter = new BufferedWriter( fileWriter );
      String line;
      String user;
      String count;
      while((line = bufferedReader.readLine() != null )
        StringTokenizer tokenizer = new StringTokenizer( line );
        if( tokenizer.countTokens != 2 ) continue; // bogus line
        user = tokenizer.nextToken;
        if( activeUser.equals( user ) )
          count = tokenizer.nextToken;
          bufferedWriter.write(user+" "+(Integer.parseInt(count)+1)+"\n" );
        else
          bufferedWriter.write( line );
      bufferedWriter.close();
      fileWriter.close();
      bufferedReader.close();
      fileReader.close();
      File oldLog = new File("mylog");
      File newLog = new File("mylog.new");
      newLog.renameTo(oldLog);
    catch( Exception e )
        // do whatever appropriate
    }Have fun,
    Klaus

Maybe you are looking for

  • Update zlspr and zlsch in ABAP program

    Hi to all, I need a way to update the fields zlspr and zlsch (table bseg) without using bdc and transaction FB09 because I want a possibility to roll back work.  Does anybody know about a FM who supports this functionality or any other way how to sol

  • Ad hoc network for Airplay Mirroring

    Can you create an ad hoc network between an Apple TV and a MacbookPro to use air play mirroring? It would be useful when there is no available wireless network?

  • Data Warehouse RAID Configuration

    Hi, We are moving from oracle 9i to 10g two of our databases. The first one is our Staging database. The second is the datawarehouse database. Most of the activity in the Staging database is writing data. Most of the activity in the datawarehouse dat

  • How to use call landlines

    Hai.. I already have subscription. It's called as Microsoft 360 subscription. Now I have 60 minutes call landline. But I don't know how to use it. My location in Jakarta. Why can't I call to my friend mobile numbers? And, what is landline?

  • HT201210 i cant update my ipod

    i keeps reseting but it stays on the usb with the simbull of the itune. its doing my head in