Learning java programing - Array issues.

Hi Everyone,
I just started in java programming and into Arrays multidimensional. I started a simple 2 dimensional array with 5 names with genders. I 'm having issues because it does not want to print out the names with correct genders Male/ Female. The simple program should print out the 5 names with gender type.
example:
Jack - Male
Sally - Female
Dave - Male
Sue - Female
Brian - Male
Here is what I came up with so far:
public class Multiname
     public static void main(String[] args)
          //String[][] multiname;
          String [][] multiname =
                    {"Jack", "sally"},
                    {"Dave", "Brian"},
                    {"Sue"}
          /* multiname [0][0] = "Jack";
          multiname [0][1] = "Male";
          multiname [1][0] = "Sally";
          multiname [1][1] = "Female";
          multiname [2][0] = "Dave";
          multiname [2][1] = "Male";
          multiname [3][0] = "Sue";
          multiname [3][1] = "Female";
          multiname [4][0] = "Brain";
          multiname [4][1] = "Male";     
          //int rows = 2;
     //int columns = 2;
               for(int i = 0; i < 4; i++)
                    {for(int j = 0; j < 2; j++)
                            System.out.println("multiname " + ": " + multiname [i][j]);               
This is the result:
multiname : Jack
multiname : sally
multiname : Dave
multiname : Brian
multiname : Sue
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
     at MultiD.main(MultiD.java:29)
Can someone inform me what is wrong or missing, and what do I need to do to correct this. I'm new to this and I'm a visual person. Any assistance would be appreciated.
Thanks,

Welcome to the forum!
When you post code use \ on the line before and on the line after the code to preserve formatting (read the FAQ). You can use the 'Preview' tab on the reply window to see what your reply will look like.
Please edit your post and add the code tags.
{quote}
The simple program should print out the 5 names with gender
{quote}
How could it possibly do that when you commented out the lines the put the gender into the arrays?/* multiname [0][0] = "Jack";
multiname [0][1] = "Male";
multiname [1][0] = "Sally";
multiname [1][1] = "Female";
multiname [2][0] = "Dave";
multiname [2][1] = "Male";
multiname [3][0] = "Sue";
multiname [3][1] = "Female";
multiname [4][0] = "Brain";
multiname [4][1] = "Male";
When you are starting out don't use any more data than you need to get things working. You only need two name/gender combinations; any more just gets in the way.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Interested in Learning Java Programming.

    Hello All,
    I a college student and I am interested in learning Java programming. Where would be a good place for me to start?
    Thanks

    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • Java programming applet issue newbie help

    hello
    i am a student taking an intro to OOP course using java. i have textMate and blue J as java editing environments. i have successfully managed a few lessons but now i am having trouble with applets. my applet source code will run in blue j but not in textmate and i think the reason has to do with the applet extension. first when i run the program successfully in blue jay it utilizes the sun.applet.main environment to display the applets output. but in textmate the identical code generates an error which i finally have a some information about why?
    the error in textmate reads
    :exception in thread "main" java.lang.NoSuchMethodError: main
    i am not sure whether this has to do with the import java.awt.*: or just the public void paint(Graphics g) method (code Below)
    the eventual intended output of the applet is to a web browser via an html document which calls the java applet but when i run this html document both firefox and safari display blank pages.
    i am on macpro with the latest java version - just downloaded last week
    is there some unique import statement to utilize import java.awt.*;
    import java.applet.*; in mac os or ???
    BTW the smile.gif is in the project folder with the java document
    thanks for any help
    Chapter 2: Welcome to My Day
    Programmer: rafe McDonald
    Date: November 5, 2009
    Filename: WelcomeApplet
    Purpose: This project displays a smile graphic, welcome message, the user's
    name, and the system date in an applet.
    import java.util.Date;
    import java.awt.*;
    import java.applet.*;
    public class WelcomeApplet extends Applet
    public void paint(Graphics g)
    Date currentDate = new Date(); //Date constructor
    g.drawString("Welcome to my day!",200,70);
    g.drawString("Daily planner for Rafe McDonald",200,100);
    g.drawString(currentDate.toString(),200,130);
    Image smile; //declare an Image object
    smile = getImage(getDocumentBase(), "smile.gif");
    g.drawImage(smile,10,10,this);
    setBackground(Color.cyan);
    }

    http://discussions.apple.com/thread.jspa?threadID=2226853&tstart=0
    i realized the other section of this forum is geared toward java inquiries so if anyone has some ideas please post there
    thanks

  • I want to learn latest Java Programming

    Hello,
    I learned Java programming in 2006 in India. I am a student of NIIT and completed Diploma in IT.
    Right now, I am SEO Manager in leading IT company.
    I want to restart my java study at my own.
    So, How can I learn latest Java programming?
    If you have any ideas so, help me.

    Mistry-Anand wrote:
    Hello,
    Right now, I am SEO Manager in leading IT company.
    I want to restart my java study at my own.
    So, How can I learn latest Java programming?
    If you have any ideas so, help me.stick to management. Your attitude shows you're well suited to that, utterly unsuited to doing work of your own that involves any independent creative thought whatsoever.

  • Learning Java - Where do I start

    I would like to learn Java programming. I have solid background in OOP. Please let me know where I can start and how I can get hands-on experience
    Thank you

    You need both good programming tools and books:
    1. download JDK131 from sun and install it;
    2. download Forte for Java 3.0 from sun and install it;
    3. download Java tutorial and other documents from sun
    and read it.
    then you can start.

  • Java 2D array program help please?

    Hi - I'm teaching computer science to myself (java, using jGRASP) using some websites online, and one of the activities I have to do is to make an "image smoother" program.
    I just started learning about 2D array, and I think I get what it is (based on what I know of 1D arrays), but I have no clue how to do this activity.
    This is what the description says:
    "A grey-level image is sometimes stores as a list of int values. The values represent the intensity of light as discrete positions in the image.
    An image may be smoothed by replacing each element with the average of the element's neighboring elements.
    Say that the original values are in the 2D array "image". Compute the smoothed array by doing this: each value 'smooth[r][c]' is the average of nine values:
    image [r-1][c-1], image [r-1][c ], image [r-1][c+1],
    image [r ][c-1], image [r ][c ], image [r ][c+1],
    image [r+1][c-1], image [r+1][c ], image [r+1][c+1].
    Assume that the image is recangular, that is, all rows have the same number of locations. Use the interger arithmetic for this so that the values in 'smooth' are integers".
    and this is what the website gives me along with the description above:
    import java.io.*;
    class Smooth
    public static void main (String [] args) throws IOException
    int [][] image = {{0,0,0,0,0,0,0,0,0,0,0,0,},
    {0,0,0,0,0,0,0,0,0,0,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,5,5,5,5,5,5,5,5,0,0},
    {0,0,0,0,0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0,0,0,0,0}};
    //assume a rectangular image
    int[][] smooth = new int [image.length][image[0].length];
    //compute the smoothed value for
    //non-edge locations in the image
    for (int row=1; row<image.length-1; row++)
    for (int col=1; col<image[row].length-1; col++)
    smooth[row][col] = sum/9;
    //write out the input
    //write out the result
    "The edges of the image are a problem because only some of the nine values that go into the average exist. There are various ways to deal with this problem:
    1. Easy (shown above): Leave all the edge locations in the smoothed image to zero. Only inside locations get an averaged value from the image.
    2. Harder: Copy values at edge locations directly to the smoothed image without change.
    3. Hard: For each location in the image, average together only those of the nine values that exist. This calls for some fairy tricky if statements, or a tricky set of for statements inside the outer two.
    Here is a sample run of the hard solution:
    c:\>java ImageSmooth
    input:
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 5 5 5 5 5 5 5 5 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    output:
    0 0 0 0 0 0 0 0 0 0 0 0
    0 0 1 1 1 1 1 1 1 1 0 0
    0 1 2 3 3 3 3 3 3 2 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 3 5 5 5 5 5 5 3 1 0
    0 1 2 3 3 3 3 3 3 2 1 0
    0 0 1 1 1 1 1 1 1 1 0 0
    0 0 0 0 0 0 0 0 0 0 0 0
    c:\>"
    OKAY that was very long, but I'm a beginner to java, especially to 2D arrays. If anyone could help me with this step-by-step, I would greatly appreciate it! Thank you very much in advance!

    larissa. wrote:
    I did try, but I have no clue where to start from. That's why I asked if someone could help me with this step by step...regardless, our track record for helping folks who state they are "completely lost" or "don't have a clue" is poor to dismal as there is only so much a forum can do in this situation. We can't put knowledge in your head; only you can do that. Often the best we can do is to point you to the most basic tutorials online and suggest that you start reading.
    That being said, perhaps we can help you if you have some basic knowledge here, enough to understand what we are suggesting, and perseverance. The first thing you need to do is to try to create this on your own as best you can, then come back with your code and with specific questions (not the "I'm completely lost" kind) that are answerable in the limited format of a Java forum. By posting your code, we can have a better idea of just where you're making bad assumptions or what Java subjects you need to read up on in the tutorials.

  • How to return array of String to a java program.! ??

    Hi All,
    I am new to JNI programming. so trying with simple example. I am having one problem. I have one array of String in my Java program. I want to reverse all the elements in this array and want back this new array in the same form i.e. array of string. So how can I do this ??
    Please guide me.....
    The function of defination of array in my java code is
    public native String[] getReverseStringArray(String[] arrString);
    where as my array is like:
    String[] arrStr = {"one", "two", "three", "four", "��������","�c��","�J�^�J�i"};
    and I am calling function in C file like:
    arrStr = employee.getReverseStringArray(arrStr);
    and the function defination in my c file is
    JNIEXPORT jobjectArray JNICALL
    Java_Emp_getReverseStringArray (JNIEnv *env, jobject obj, jobjectArray arr)
    // some code will come here......
    So can anybody tell me how to do this ??
    Thanx in advance...
    Pandurang
    [email protected]

    Hi,
    this is quite simple. Here an example function that works like this:
    JNIEXPORT jobjectArray JNICALL Java_cadagent_ugopen_UgAssembly_jni_1getStructure
    (JNIEnv *env, jclass cls, jstring part)
    jobjectArray retvals = NULL;
    jstring j_val = NULL;
    int child_count = 5;
    /* initialize return array */
    j_val = (*env)->NewStringUTF(env, "");
    retvals = (*env)->NewObjectArray(env, child_count, (*env)->FindClass(env, "java/lang/String"), j_val);
    for (i=0;i<child_count;i++)
    j_val = (*env)->NewStringUTF(env, "some text");
    (*env)->SetObjectArrayElement(env, retvals,i, j_val);
    return retvals;
    Hope this answers you question.

  • Example java programs to learn from?

    Hi. I just finished the Head First Book and I am about to start on the 1.5 certification book. In the mean time, I was wondering what open source projects might be good for me to download and start reading the code for? I thought it might be a good idea to download one and go through the code, marking it up with what I think it is doing and looking up things I don't understand. Any pointers to good software to do that on, would be great!
    Sorry if this is the wrong forum.
    Mark

    hey eko291!
    I found that the easiest way to learn java was to do something with it. I set up a sourceforge site, and set about making widgets for swing that were non standard in java but found in other languages/operating systems. Looking at code to learn is a two-edged sword. On the one hand it can be great for ideas, but on the other, some people really write cruddy obfuscated code that is a nightmare to follow, let alone learn from.
    Write some of your own stuff first to get really familiar with it. If you get stuck, look at some examples from Java Almanac (blood good site that one). Look for some examples from O'Reilly books etc.
    I wrote some code to help me learn java. While looking at it to learn Java is not something I would recommend, you may find getting ideas from it to help out with your own projects is something useful.
    Feel free. www.sf.net/projects/avianfs
    Also, I got a lot of good ideas from a particular guy's blog. Romain Guy. He posts up some really super code for people interested in UI design. Looking through his code, you will be amazed at some of the things you can do with Java. You will get heaps of ideas from there.
    hope that helps!
    Jason Barraclough.
    Message was edited by:
    fireman.sparkey
    because he realised that a word he used was a naughty one...

  • Writing a java program for generating .pdf file with the data of MS-Excel .

    Hi all,
    My object is write a java program so tht...it'll generate the .pdf file after retriving the data from MS-Excel file.
    I used POI HSSF to read the data from MS-Excel and used iText to generate .pdf file:
    My Program is:
    * Created on Apr 13, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package forums;
    import java.io.*;
    import java.awt.Color;
    import com.lowagie.text.*;
    import com.lowagie.text.pdf.*;
    import com.lowagie.text.Font.*;
    import com.lowagie.text.pdf.MultiColumnText;
    import com.lowagie.text.Phrase.*;
    import net.sf.hibernate.mapping.Array;
    import org.apache.poi.hssf.*;
    import org.apache.poi.poifs.filesystem.*;
    import org.apache.poi.hssf.usermodel.*;
    import com.lowagie.text.Phrase.*;
    import java.util.Iterator;
    * Generates a simple 'Hello World' PDF file.
    * @author blowagie
    public class pdfgenerator {
         * Generates a PDF file with the text 'Hello World'
         * @param args no arguments needed here
         public static void main(String[] args) {
              System.out.println("Hello World");
              Rectangle pageSize = new Rectangle(916, 1592);
                        pageSize.setBackgroundColor(new java.awt.Color(0xFF, 0xFF, 0xDE));
              // step 1: creation of a document-object
              //Document document = new Document(pageSize);
              Document document = new Document(pageSize, 132, 164, 108, 108);
              try {
                   // step 2:
                   // we create a writer that listens to the document
                   // and directs a PDF-stream to a file
                   PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream("c:\\weeklystatus.pdf"));
                   writer.setEncryption(PdfWriter.STRENGTH128BITS, "Hello", "World", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
    //               step 3: we open the document
                             document.open();
                   Paragraph paragraph = new Paragraph("",new Font(Font.TIMES_ROMAN, 13, Font.BOLDITALIC, new Color(0, 0, 255)));
                   POIFSFileSystem pofilesystem=new POIFSFileSystem(new FileInputStream("D:\\ESM\\plans\\weekly report(31-01..04-02).xls"));
                   HSSFWorkbook hbook=new HSSFWorkbook(pofilesystem);
                   HSSFSheet hsheet=hbook.getSheetAt(0);//.createSheet();
                   Iterator rows = hsheet.rowIterator();
                                  while( rows.hasNext() ) {
                                       Phrase phrase=new Phrase();
                                       HSSFRow row = (HSSFRow) rows.next();
                                       //System.out.println( "Row #" + row.getRowNum());
                                       // Iterate over each cell in the row and print out the cell's content
                                       Iterator cells = row.cellIterator();
                                       while( cells.hasNext() ) {
                                            HSSFCell cell = (HSSFCell) cells.next();
                                            //System.out.println( "Cell #" + cell.getCellNum() );
                                            switch ( cell.getCellType() ) {
                                                 case HSSFCell.CELL_TYPE_STRING:
                                                 String stringcell=cell.getStringCellValue ()+" ";
                                                 writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                 phrase.add(stringcell);
                                            // document.add(new Phrase(string));
                                                      System.out.print( cell.getStringCellValue () );
                                                      break;
                                                 case HSSFCell.CELL_TYPE_FORMULA:
                                                           String stringdate=cell.getCellFormula()+" ";
                                                           writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                           phrase.add(stringdate);
                                                 System.out.print( cell.getCellFormula() );
                                                           break;
                                                 case HSSFCell.CELL_TYPE_NUMERIC:
                                                 String string=String.valueOf(cell.getNumericCellValue())+" ";
                                                      writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                      phrase.add(string);
                                                      System.out.print( cell.getNumericCellValue() );
                                                      break;
                                                 default:
                                                      //System.out.println( "unsuported sell type" );
                                                      break;
                                       document.add(new Paragraph(phrase));
                                       document.add(new Paragraph("\n \n \n"));
                   // step 4: we add a paragraph to the document
              } catch (DocumentException de) {
                   System.err.println(de.getMessage());
              } catch (IOException ioe) {
                   System.err.println(ioe.getMessage());
              // step 5: we close the document
              document.close();
    My Input from MS-Excel file is:
         Planning and Tracking Template for Interns                                                                 
         Name of the Intern     N.Kesavulu Reddy                                                            
         Project Name     Enterprise Sales and Marketing                                                            
         Description     Estimated Effort in Hrs     Planned/Replanned          Actual          Actual Effort in Hrs     Complexity     Priority     LOC written new & modified     % work completion     Status     Rework     Remarks
    S.No               Start Date     End Date     Start Date     End Date                                        
    1     setup the configuration          31/01/2005     1/2/2005     31/01/2005     1/2/2005                                        
    2     Deploying an application through Tapestry, Spring, Hibernate          2/2/2005     2/2/2005     2/2/2005     2/2/2005                                        
    3     Gone through Componentization and Cxprice application          3/2/2005     3/2/2005     3/2/2005     3/2/2005                                        
    4     Attend the sessions(tapestry,spring, hibernate), QBA          4/2/2005     4/2/2005     4/2/2005     4/2/2005                                        
         The o/p I'm gettint in .pdf file is:
    Planning and Tracking Template for Interns
    N.Kesavulu Reddy Name of the Intern
    Enterprise Sales and Marketing Project Name
    Remarks Rework Status % work completion LOC written new & modified Priority
    Complexity Actual Effort in Hrs Actual Planned/Replanned Estimated Effort in Hrs Description
    End Date Start Date End Date Start Date S.No
    38354.0 31/01/2005 38354.0 31/01/2005 setup the configuration 1.0
    38385.0 38385.0 38385.0 38385.0 Deploying an application through Tapestry, Spring, Hibernate
    2.0
    38413.0 38413.0 38413.0 38413.0 Gone through Componentization and Cxprice application
    3.0
    38444.0 38444.0 38444.0 38444.0 Attend the sessions(tapestry,spring, hibernate), QBA 4.0
                                       The issues i'm facing are:
    When it is reading a row from MS-Excel it is writing to the .pdf file from last cell to first cell.( 2 cell in 1 place, 1 cell in 2 place like if the row has two cells with data as : Name of the Intern: Kesavulu Reddy then it is writing to the .pdf file as Kesavulu Reddy Name of Intern)
    and the second issue is:
    It is not recognizing the date format..it is recognizing the date in first row only......
    Plz Tell me wht is the solution for this...
    Regards
    [email protected]

    Don't double post your question:
    http://forum.java.sun.com/thread.jspa?threadID=617605&messageID=3450899#3450899
    /Kaj

  • Challange for you, help for me! java program

    I am a beginning java student and desparately (again) in help of someone who will check my java program. See below what they want from me, and try to make a program of it that works in all the ways that are asked. Thank you for helping me, i am running out of time.
    Prem Pradeep
    [email protected]
    Catalogue Manager II
    Specification:
    1.     Develop an object to represent to encapsulate an item in a catalogue. Each CatalogueItem has three pieces of information: an alphanumeric catalogue code, a name, and a price (in dollars and cents), that excludes sales tax. The object should also be able to report the price, inclusive of a 15% sales tax, and the taxed component of the price.
    2.     Data input will come from a text file, whose name is passed in as the first command-line argument to the program. This data file may include up to 30 data items (the program will need to be able to support a variable number of actual items in the array without any errors).
    3.     The data lines will be in the format: CatNo:Description:Price Use a StringTokenizer object to separate these data lines into their components.
    4.     A menu should appear, prompting the user for an action:
    a.     Display all goods: this will display a summary (in tabulated form) of all goods currently stored in the catalogue: per item the category, description, price excluding tax, payable tax and price including tax.
    b.     Dispfay cheapest/dearest goods: this will display a summary of all the cheapest and most expensive item(s) in the catalogue. In the case of more than one item being the cheapest (or most expensive), they should all be listed.
    c.     Sort the list: this will use a selection sort algorithm to sort the list in ascending order, using the catalogue number as the key.
    d.     Search the list: this will prompt the user for a catalogue number, and use a binary search to find the data. If the data has not yet been sorted, this menu option should not operate, and instead display a message to the user to sort the data before attempting a search
    5.     Work out a way to be able to support the inc tax/ex tax price accessors, and the tax component accessor, without needing to store any additional information in the object.
    6.     Use modifiers where appropriate to:
    a.     Ensure that data is properly protected;
    b.     Ensure that the accessors and mutators are most visible;
    c.     The accessors and mutators for the catalogue number and description cannot be overridden.
    d.     The constant for the tax rate is publicly accessible, and does not need an instance of the class present in order to be accessible.
    7.     The program should handle all exceptions wherever they may occur (i.e. file 1/0 problems, number formatting issues, etc.) A correct and comprehensive exception handling strategy (leading to a completely robust program) will be necessary and not an incomplete strategy (i.e. handling incorrect data formats, but not critical errors),
    Sample Execution
    C:\> java AssignmentSix mydata.txt
    Loading file data from mydata.txt ...17 item(s) OK
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    The goods cannot be searched, as the list is not yet sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: b
    CHEAPEST GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    BA023      Headphones      23.00      3.45      26.45
    JW289      Tape Recorder     23.00      3.45      26.45
    MOST EXPENSIVE GOODS IN CATALOGUE
    Cat      Description      ExTax      Tax      IncTax
    ZZ338      Wristwatch      295.00 44.25      339.25
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: c
    The data is now sorted.
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: d
    Enter the catalogue number to find: ZJ282
    Cat Description ExTax Tax IncTax
    ZJ282 Pine Table 98.00 14.70 112.70
    CATALOGUE MANAGER: MAIN MENU
    ============================
    a) display all goods b) display cheapest/dearest goods
    c) sort the goods list d) search the goods list
    e) quit
    Option: e
    Here you have the program as far as I could get. Please try to help me make it compact and implement a sorting method.
    Prem.
    By the way: you can get 8 Duke dollars (I have this topic also in the beginnersforum)
    //CatalogueManager.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.StringTokenizer;
    public class CatalogueManager {
    // private static final double TAXABLE_PERCENTAGE = 0.15;
    // Require it to be publicly accessible
    // static means it is class variable, not an object instance variable.
    public static final double TAXABLE_PERCENTAGE = 0.15;
    private String catalogNumber;
    private String description;
    private double price;
    /** Creates a new instance of CatalogueManager */
    public CatalogueManager() {
    catalogNumber = null;
    description = null;
    price = 0;
    public CatalogueManager(String pCatalogNumber, String pDescription, double pPrice) {
    catalogNumber = pCatalogNumber;
    description = pDescription;
    price = pPrice;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setCatalogNumnber(String pCatalogNumber) {
    catalogNumber = pCatalogNumber;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final String getCatalogNumber() {
    String str = catalogNumber;
    return str;
    // the mutators must be most visible
    // the final keyword prevents overridden
    public final void setDescription(String pDescription) {
    description = pDescription;
    // the accessors must be most visible
    // the final keyword prevents overridden
    public final String getDescription() {
    String str = description;
    return str;
    // If the parameter is not a double type, set the price = 0;
    // the mutators must be most visible
    public boolean setPrice(String pPrice) {
    try {
    price = Double.parseDouble(pPrice);
    return true;
    catch (NumberFormatException nfe) {
    price = 0;
    return false;
    // the accessors must be most visible
    public double getPrice() {
    double rprice = price;
    return formatDouble(rprice);
    double getTaxAmount(){
    double rTaxAmount = price * TAXABLE_PERCENTAGE;
    return formatDouble(rTaxAmount);
    double getIncTaxAmount() {
    double rTaxAmount = price * (1 + TAXABLE_PERCENTAGE);
    return formatDouble(rTaxAmount);
    double formatDouble(double value) {
    DecimalFormat myFormatter = new DecimalFormat("###.##");
    String str1 = myFormatter.format(value);
    return Double.parseDouble(str1);
    public static void main(String[] args) throws IOException {
    final int MAX_INPUT_ALLOW = 30;
    int MAX_CURRENT_INPUT = 0;
    FileReader fr;
    BufferedReader br;
    CatalogueManager[] catalogList = new CatalogueManager[MAX_INPUT_ALLOW];
    String str;
    char chr;
    boolean bolSort = false;
    double cheapest = 0;
    double mostExpensive = 0;
    String header = "Cat\tDescription\tExTax\tTax\tInc Tax";
    String lines = "---\t-----------\t------\t---\t-------";
    if (args.length != 1) {
    System.out.println("The application expects one parameter only.");
    System.exit(0);
    try {
    fr = new FileReader(args[0]);
    br = new BufferedReader(fr);
    int i = 0;
    while ((str = br.readLine()) != null) {
    catalogList[i] = new CatalogueManager();
    StringTokenizer tokenizer = new StringTokenizer(str, ":" );
    catalogList.setCatalogNumnber(tokenizer.nextToken().trim());
    catalogList[i].setDescription(tokenizer.nextToken().trim());
    if (! catalogList[i].setPrice(tokenizer.nextToken())){
    System.out.println("The price column cannot be formatted as dobule type");
    System.out.println("Application will convert the price to 0.00 and continue with the rest of the line");
    System.out.println("Please check line " + i);
    if (catalogList[i].getPrice() < cheapest) {
    cheapest = catalogList[i].getPrice();
    if (catalogList[i].getPrice() > mostExpensive) {
    mostExpensive = catalogList[i].getPrice();
    i++;
    fr.close();
    MAX_CURRENT_INPUT = i;
    catch (FileNotFoundException fnfe) {
    System.out.println("Input file cannot be located, please make sure the file exists!");
    System.exit(0);
    catch (IOException ioe) {
    System.out.println(ioe.getMessage());
    System.out.println("Application cannot read the data from the file!");
    System.exit(0);
    boolean bolLoop = true;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    do {
    System.out.println("");
    System.out.println("CATALOGUE MANAGER: MAIN MENU");
    System.out.println("============================");
    System.out.println("a) display all goods b) display cheapest/dearest goods");
    System.out.println("c) sort the goods list d) search the good list");
    System.out.println("e) quit");
    System.out.print("Option:");
    try {
    str = stdin.readLine();
    if (str.length() == 1){
    str.toLowerCase();
    chr = str.charAt(0);
    switch (chr){
    case 'a':
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'b':
    System.out.println("");
    System.out.println("CHEAPEST GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == cheapest){
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    System.out.println("MOST EXPENSIVE GODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_CURRENT_INPUT; i++){
    if (catalogList[i].getPrice() == mostExpensive) {
    System.out.println(catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    System.out.println("");
    break;
    case 'c':
    if (bolSort == true){
    System.out.println("The data has already been sorted");
    else {
    System.out.println("The data is not sorted");
    break;
    case 'd':
    break;
    case 'e':
    bolLoop = false;
    break;
    default:
    System.out.println("Invalid choice, please re-enter");
    break;
    catch (IOException ioe) {
    System.out.println("ERROR:" + ioe.getMessage());
    System.out.println("Application exits now");
    System.exit(0);
    } while (bolLoop);

    One thing you're missing totally is CatalogueItem!! A CatalogueManager manages the CatalogueItem's, and is not an CatalogueItem itself. So at least you have to have this one more class CatalogueItem.
    public class CatalogueItem {
    private String catalogNumber;
    private String description;
    private double price;
    //with all proper getters, setters.
    Then CatalogueManager has a member variable:
    CatalogueItem[] items;
    Get this straight and other things are pretty obvious...

  • My first java programming - Need some help please!!!

    I have to create a simple java program which i am not good at i am ok in C but my java is quite bad. The program need to define a class called Student and with a string called StudentNAme, a integer StudentID(key), An array of 8 integers called Marks that holds the students marks for 8 modules. It also says Include appropriate accessors, mutators and constructor(s) as well as a method to update the student�s marks. Anybody please help me in this question. I prefer an simple example of this program so I can learn faster, I dont even know how to declare a class.. So sorry but please help me out and thanks in advance

    I would also suggest you try using an IDE like
    eclipse (free)
    www.eclipse.org
    This will help you get a working program much faster.But please do also tell them that if they have troubles using it, they're supposed to read the IDE manual instead of posting here.

  • I need to call a java program and pass parameters from C#

    I'm new to C# and was given a project to rewrite some of my old VB.net programs to C# to help me learn.  These VB programs call quite a few .bat files that have calls to java programs in them. I'm doing okay converting my VB code, but I've been
    stumped for days trying to figure out how to call java from C#. 
    Does anyone here know how to do this?  I really should've had this figured out by now and my back is to the wall.  Ugh :(
    This is the line from the .bat file that I need to convert to C#. 
    call jvbat production_r115.Automotive m:\data\MK115mn.100 m:\data\MK115mn.101 %6
    There is one parameters being passed, %6
    I would be forever grateful if someone can show me how to do this!

    Hi Joni,
    Do you mean call a bat file that it is a Java program from C#?  If so, there is an article talking about it.
    If that's not what you're trying to do, please be more specific about what you're trying to do.
    http://www.c-sharpcorner.com/UploadFile/maheswararao/CallingJavaProgramfromCS12062005233321PM/CallingJavaProgramfromCS.aspx
    Now the next issue is pass some parameters from C#.
    The above article tells using Process.Start() method to call java program. Also  in this class, you could  specify them all in the
    Arguments property:
    var p = new Process();
    p.StartInfo.Arguments = string.Format("{0} {1}", argument1, argument2);
    For more detailed information, please refer to
    C# Passing Multiple Arguments to BAT File
    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control
    these sites and has not tested any software or information found on these sites;
    Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information
    found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Links to learn Java

    Hi,
    I friend of mine has just started learning Java. Can you reccomend any tutorial sessions on the web or some books?
    Thank you very much
    Maria

    By all means, please direct your friend to the JDC's:
    New to Java Programming Center: http://developer.java.sun.com/developer/onlineTraining/new2java/
    Have your friend subscribe to the center's monthly email supplement and read past issues online:
    http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/
    As for books, have your friend read this article:
    Books to Shorten Your Learning Curve:
    http://developer.java.sun.com/developer/onlineTraining/new2java//programming/learn/bookreview.html
    Then have your friend check out our tutorials:
    http://developer.java.sun.com/developer/onlineTraining/
    Starting with the New to Java Programming Center because that is the collection of beginner material all linked in one convenient spot.
    Enjoy!
    Dana Nourie

  • Problem with running java program

    Hey again!
    I missed out some information in last posting.. here is the full description
    I have just installed 1.5.0_06 and have set paths and what otherwise is necessary to run the java programs. I was testing the install and run a standard HelloWorld.java program
    I got the following error:
    Exception in thread main java.lang.NoClassDefFoundError: HelloWorld
    what is wrong...
    Here is the entire HelloWorld.java
    public class HelloWorld
    public HelloWorld()
    System.out.println("Hello World");
    public static void main(String[] args)
    HelloWorld hw = new HelloWorld();
    I have checked that the path is correct too..
    Hopefully someone can help me!
    Anders

    Your Path is set, probably the problem is classpath.
    Change the cmd/command prompt to the directory that contains your HelloWorld.class file, verifying that it exists. If it does, issue this command from that directory:
    java -cp . HelloWorld
    Important: include the period and surrounding spaces
    If that works, you can learn about setting and using the classpath here:
    http://java.sun.com/j2se/1.5.0/docs/tooldocs/index.html#general
    By the way, just add a reply to your original post with the additional information, rather than creating another post. That eliminates duplication of replies.

  • Need some java help - arrays

    I've been learning java for the past few weeks and I'mstuck with the following question:
    Write a short program to store the input values of a user-specified amount of whole numbers and output them in a multipcation matrix form, with correct formatting.
    For example, the input of of three numbers 1, 2 and 3 would produce the followinf matrix:
    *1 2 3*
    *2 4 6*
    *3 6 9*
    or the input of 4 numbers 3,7, 4 and 9 would produce the following matrix:
    *3 7 4 9*
    *7 49 28 63*
    *4 28 16 36*
    *9 63 36 81*
    whereby the inner numbers in the grid represent the product of the number on the corresponding top row and left most column, i.e 36 = 9 4*
    The user must be initially be allowed to specify how many numbers they wish to enter, followed by the number themselves. You must maked use of an array for this exercise. Ensure the proper formatting rules are adhered to, i.e. that all columns are aligned vertically (right justified). You can assume no input number greater than 100 will be entered.
    I was wondering if someone could help me with this?

    Or better yet:
    [] 3  7  4  9
    3  9 21 12 27
    7 21 49 28 63
    4 12 28 16 36
    9 27 63 36 81which is i am sure what you were after flounder, the formatting for some reason kept moving the top row over to the left.
    P.S. If the OP is still here...here is a bit of a head start.
    public static void main(String[] args) {
           Scanner sc1 = new Scanner(System.in);
           int[] array;
           int x;
           int y;
           System.out.println("How many numbers do you want to enter? ");
           x = sc1.nextInt();
           array = new int[x];
           System.out.println("Please enter your numbers ");
           for (int i=0;i<x;i++){
               y = sc1.nextInt();
               array=y;
    //test printing contents of array
    System.out.println("--------------");
    System.out.println();
    System.out.println("OUTPUT");
    System.out.println();
    System.out.println("--------------");
    for(int j=0;j<array.length;j++){
    System.out.print(array[j]);

Maybe you are looking for