Please help with my helper class

Hi,
plz I need some assistance with this:
I have a big table which consist of 200 columns. This table gets fields from different tables. It has records of orders which may have several items and each item can have up to 8 taxes. So i have fields reaping for other order order records. I need to display an order then have a navigation to list items in details, with all its taxes, one by one.
Here is how I have decided to do it in a nutshell. I have decided to get all taxes of a particular item and put in a map with tax_codes as values and tax details arraylist as values. I then add this to an item with its other details. then I add items to a particular order. I have separated orders,items and taxes in their separate beans. Im trying to first the implimentation for each order, item and taxes by displaying them on a JSP. However am currently getting the following error with taxdetails:
java.lang.ClassCastException: OrderItems.ItemTax cannot be cast to java.lang.String
at OrderItems.OrderDetails.getItemTaxDetails(OrderDetails.java:166)
at OrderItems.Controller.processRequest(Controller.java:57)
at OrderItems.Controller.doGet(Controller.java:72)
I have a list of all itemTaxCodes am iterating and am casting to string...am not casting ItemTax object.Here is my code below:
OrderDetails.java
package orderitems;
import java.sql.*;
import java.util.*;
public class OrderDetails {
    private LineOder lineOrder;
    private Map lineItems;
    //returns an item number, key_item, from its unique keys
    public int getItemNumber(int key_item, String key_year,
            String key_office,String key_client,String key_company){
        Connection conn = null;
        Statement stat = null;
        ResultSet rst = null;
        int itmNum = 0;
         * key_item a unique number for an item.
         * key_year,key_office,key_client,key_company unique keys
         * for each order where this key_item is taken
         * from.
        String select = "SELECT key_item FROM "+
                Constants.WEB_TABLE +" WHERE key_item = " + key_item +
                " AND key_year = '" + key_year + "'" +
                " AND key_office = '" + key_office + "'" +
                " AND key_client = '" + key_client + "'" +
                " AND key_company = '" + key_company +"'";
        DbConnection dbConn = new DbConnection();
        try {
            conn = dbConn.getDbConnection(Constants.WEB_JNDI);
            stat = conn.createStatement();
            rst = stat.executeQuery(select);
            if(rst.next()){
                itmNum = Integer.parseInt(rst.getString("key_item"));
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally{
            SQLHelper.cleanUp(rst, stat, conn);
        return itmNum;
    //get a list of item number(item codes)
    public List getAllItemNumbers(String key_year,
            String key_office,String key_client,String key_company){
        List itemNumbers = new ArrayList();
        LineItem itemNumber = null;
        Connection conn = null;
        Statement stat = null;
        ResultSet rst = null;
        String select = "SELECT key_item FROM "+ Constants.WEB_TABLE +
                " WHERE key_year = '" + key_year + "'" +
                " AND key_office = '" + key_office + "'" +
                " AND key_client = '" + key_client + "'" +
                " AND key_company = '" + key_company + "'";
        DbConnection dbConn = new DbConnection();
        try {
            conn = dbConn.getDbConnection(Constants.WEB_JNDI);
            stat = conn.createStatement();
            rst = stat.executeQuery(select);
            while(rst.next()){
                itemNumber = new LineItem();
                itemNumber.setKey_item(Integer.parseInt(rst.getString("key_item")));
                itemNumbers.add(itemNumber);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally{
            SQLHelper.cleanUp(rst, stat, conn);
        return itemNumbers;
    //get a list of tax codes
    public List getAllTaxCodes(int key_item, String key_year,
            String key_office,String key_client,String key_company){
        Connection conn = null;
        Statement stat = null;
        ResultSet rst = null;
        ItemTax taxCode;
        List taxCodes = new ArrayList();
        int itemNum = getItemNumber(key_item, key_year,
                key_office,key_client,key_company);
        String select = "SELECT key_tax_code FROM "+
                Constants.WEB_TABLE +" WHERE key_item = " + itemNum +
                " AND key_year = '" + key_year + "'" +
                " AND key_office = '" + key_office + "'" +
                " AND key_client = '" + key_client + "'" +
                " AND key_company = '" + key_company +"'";
        DbConnection dbConn = new DbConnection();
        try {
            conn = dbConn.getDbConnection(Constants.WEB_JNDI);
            stat = conn.createStatement();
            rst = stat.executeQuery(select);
            while(rst.next()){
                taxCode = new ItemTax();
                taxCode.setKey_tax_code(rst.getString("key_tax_code"));
                taxCodes.add(taxCode);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally{
            SQLHelper.cleanUp(rst, stat, conn);
        return taxCodes;
    //use tax code to get tax details
    public Map getItemTaxDetails(String key_year,String key_office,
            String key_client,String key_company,int key_item){
        ItemTax taxDetail = null;
        List taxDetails = new ArrayList();
        List itemTaxCodes = new ArrayList();
        Map itemTaxdetails = new HashMap();
        Connection conn = null;
        Statement stat = null;
        ResultSet rst = null;
        //get a list of all tax codes of an item with a
        //given item number
        itemTaxCodes = getAllTaxCodes(key_item,key_year,///a list of tax codes
                key_office,key_client,key_company);
        DbConnection dbConn = new DbConnection();
        try {
            conn = dbConn.getDbConnection(Constants.WEB_JNDI);
            stat = conn.createStatement();
            for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                String taxCode = (String)taxCodeIter.next();/////casting taxtCode to string***exception occurs from here
                String select = "SELECT tax_type,tax_value," +
                        "tax_limit_val FROM "+ Constants.WEB_TABLE +
                        " WHERE key_item = "+ key_item +
                        " AND key_year = '" + key_year + "'" +
                        " AND key_office = '" + key_office + "'" +
                        " AND key_client = '" + key_client + "'" +
                        " AND key_company = '" + key_company +"'" +
                        " AND key_tax_code = '" + taxCode + "'";///tax code string
                rst = stat.executeQuery(select);
                while(rst.next()){
                    taxDetail = new ItemTax();
                    //records to be displayed only
                    taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                    taxDetail.setTax_value(rst.getString("tax_value"));
                    taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                    //////other details records ommited//////////////////////////
                    taxDetails.add(taxDetail);
            //a HashMap of all tax code as keys and list of details as values 4 each key
            for(int i = 0;i<itemTaxCodes.size(); i++){
                itemTaxdetails.put(itemTaxCodes.get(i),taxDetails.get(i));
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally{
            SQLHelper.cleanUp(rst, stat, conn);
        return itemTaxdetails;
    //details of an item with all its taxes
    public List getAllItemDetails(String key_year,
            String key_office,String key_client,String key_company){
        List lineItems = new ArrayList();
        List itemNumbers = new ArrayList();
        Map taxDetails = new HashMap();
        LineItem item = null;
        Connection conn = null;
        Statement stat = null;
        ResultSet rst = null;
        //A list of all item numbers in the declaration
        itemNumbers = getAllItemNumbers(key_year,
                key_office,key_client,key_company);
        DbConnection dbConn = new DbConnection();
        try {
            conn = dbConn.getDbConnection(Constants.WEB_JNDI);
            stat = conn.createStatement();
            for(Iterator itemIter= itemNumbers.iterator(); itemIter.hasNext();){
                int itemNumber = ((Integer)itemIter.next()).intValue();
                String select = "SELECT item_description,item_mass," +
                        "item_cost" +
                        " FROM " + Constants.WEB_TABLE +
                        " WHERE key_year = '"+key_year+"'" +
                        " AND key_office = '"+key_office+ "'"+
                        " AND key_client = '"+key_client+ "'"+
                        " AND key_company = '"+key_company+ "'"+
                        " AND key_item = " + itemNumber;
                rst = stat.executeQuery(select);
                while(rst.next()){
                    item = new LineItem();
                    item.setItem_description(rst.getString("item_description"));
                    item.setItem_mass(Float.parseFloat(rst.getString("item_mass")));
                    item.setKey_item(Integer.parseInt(rst.getString("item_cost")));
                    //////other details records ommited//////////////////////////
                    //A HashMap of all itemTaxeCodes as its keys and an ArrayList of itemTaxedetails as its values
                    taxDetails = getItemTaxDetails(item.getKey_year(),item.getKey_office(),
                            item.getKey_client(),item.getKey_company(),item.getKey_item());
                    //item tax details
                    item.setItmTaxes(taxDetails);
                    //list of items with tax details
                    lineItems.add(item);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally{
            SQLHelper.cleanUp(rst, stat, conn);
        return lineItems;
    public Set getDeclarations(String key_year,String key_cuo,
            String key_dec,String key_nber){
        List lineItems = new ArrayList();
        Set lineOrders = new HashSet();
        Connection conn = null;
        Statement stat = null;
        ResultSet rst = null;
        LineOder lineOrder = null;
        String select = "SELECT * FROM " + Constants.WEB_TABLE +
                " WHERE key_year = '" + key_year + "'" +
                " AND key_cuo = '" + key_cuo + "'" +
                " AND key_dec = '" + key_dec + "'" +
                " AND key_nber = '" + key_nber + "'";
        DbConnection dbConn = new DbConnection();
        try {
            conn = dbConn.getDbConnection(Constants.WEB_JNDI);
            stat = conn.createStatement();
            rst = stat.executeQuery(select);
            while(rst.next()){
                lineOrder = new LineOder();
                lineOrder.setKey_year(rst.getString("key_year"));
                lineOrder.setKey_office(rst.getString("key_cuo"));
                lineOrder.setKey_client(rst.getString("key_dec"));
                lineOrder.setKey_company(rst.getString("key_nber"));
                ////list of items with all their details
                lineItems = getAllItemDetails(lineOrder.getKey_year(),lineOrder.getKey_office(),
                        lineOrder.getKey_client(),lineOrder.getKey_company());
                //setting item details
                lineOrder.setItems(lineItems);
                //a list of order with all details
                lineOrders.add(lineOrder);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally{
            SQLHelper.cleanUp(rst, stat, conn);
        return lineOrders;
} and my testing servlet controller
Controller.java
package orderitems;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Controller extends HttpServlet {
    private Map taxDetails = new HashMap();
    //private List itemDetails = new ArrayList();
    //private Set orderDetails = new HashSet();
    private OrderDetails orderDetails = null;
    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)throws
            ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String key_year = "2007";
        String key_office = "VZX00";
        String key_company = "DG20";
        String key_client =  "ZI001";
        int key_item = 1;
        String nextView = "/taxdetails_list.jsp";
        //String nextView = "/order_list.jsp";
        //String nextView = "/items_list.jsp";
        orderDetails = new OrderDetails();
        taxDetails = orderDetails.getItemTaxDetails(key_year,key_office,
                key_company,key_client,key_item);
        //Store the collection objects into HTTP Request
        request.setAttribute("taxDetails", taxDetails);
        RequestDispatcher reqstDisp =
                getServletContext().getRequestDispatcher(nextView);
        reqstDisp.forward(request,response);
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response)throws
            ServletException, IOException {
        processRequest(request, response);
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response)throws
            ServletException, IOException {
        processRequest(request, response);
}I have not included code for beans to reduce on bulk.please help and with suggestions...
Thanx in advance.
Edited by: aiEx on Oct 3, 2007 8:13 AM

aiEx wrote:
sometimes a tap on the head is needed to really learn and understand :-)You're casting them to the String type while they are of the ItemTax type and you've confirmed it yourself. Likely you misunderstood the concepts behind "casting" and you was expecting some magic that they are automatically converted somehow from the ItemTax type to the String type while the ItemTax class isn't a subclass of the String class :)

Similar Messages

  • Help with Mac Help Viewer

    Hello to whoever is looking at this posting. This may be somewhat out of the norm, but for some odd reason, if I ever try to use the Help function in finder, nothing displays. I just get a blank screen with the "ask a question column", but it acts like it is trying to load continuously. I have to force quit to exit.
    Does anyone know why this would be or if there is a specific software update to rectify this problem. This machine is still under 1 year basic warrenty, would it make sense to contact support for this? I have no other software conflicts which is the weird thing. Im using Mac OSX Version 10.3.9.
    Thank you for any help with this help issue!
    Andrew

    Help Viewer crashes or shows blank....
    http://discussions.info.apple.com/webx?[email protected]@.6897a2ae http://www.thexlab.com/faqs/helpviewer.html
    This is a common bug in Panther. The solution to this problem is simple though:
    • (~ means your home directory)
    Go to ~/Library/Preferences and delete the following files.....
    com.apple.help.plist
    com.apple.helpui.plist (you may or may not have this one).
    com.apple.helpviewer.plist
    Next go to ~/Library/Caches and delete the folder......
    com.apple.helpui
    Log out and log in. If the problem is gone, empty the trash. If not, put everything back.
    or you can open MacHelp directly from .....
    /Library/Documentation/Help and it works fine.
    george
    iMac Flat Panel 1.25GHz 80GB 256MB   Mac OS X (10.3.9)  

  • Please help with the URL class

    Hello,
    I am trying to write a Java app that will take a url and download it.
    I believe you can do this with the URL class but I don't understand how to. For example, if the http url location points to a picture file, how would I code the app to retrieve this picture and save it to a specified directory?
    Also, is there a way that my java app could open another program, let's say Microsoft Internet Explorer?
    Please be as specific as possible, thanks!

    You'll see below an example to download a file
    private static String copyFile (String url, String nomFichier){
         // construction du fichier de sortie
         File outputFile = new File(repertoire + "\\fichiers\\" + nomFichier);
         // si le fichier existe d�j�, il ne sert � rien de le t�l�charger !
    if (outputFile.exists())
         return "fichiers/" + nomFichier;
              try {     
         HttpURLConnection connect = (HttpURLConnection)new URL(url).openConnection();
    boolean connected = false;
    while (!connected){
    try {
    connect.connect();
    connected = true;
         catch (java.io.IOException e1) { System.out.print("...Tentative de connection"); }     
    DataInputStream reader = new DataInputStream(
    connect.getInputStream());
         FileOutputStream out = new FileOutputStream(outputFile);
         int length = 1024;
         byte[] buf = new byte[length];
         int offset = 0;
         long offsetCourant = 0;
         int nb=0;
         while ((nb=reader.read(buf,offset,length))!= -1) {
              out.write(buf,0,nb);
         out.close();
         catch (java.net.MalformedURLException e) { System.out.println("pb d'url"); }
         catch (java.io.IOException e1) { System.out.println(e1.getMessage()); }
         return "fichiers/" + nomFichier;
    }

  • I need help with the https class please.

    Hello, i need add an authentication field in my GET request using HTTPS to authenticate users. I put the authentication field using the setRequestProperty method, but it doesn't appear when i print all properties using the getRequestProperties method. I wrote the following code:
    try{
    URL url = new URL ("https://my_url..");
    URLConnection conexion;
    conexion = url.openConnection();
    conexion.setRequestProperty("Authorization",my_urlEncoder_string);
    conexion.setRequestProperty("Host",my_loginServer);
    HttpsURLConnection httpsConexion = (HttpsURLConnection) conexion;
    httpsConexion.setRequestMethod("GET");
    System.out.println("All properties\r\n: " + httpsConexion.getRequestProperties());
    }catch ....
    when i run the program it show the following text:
    All properties: {Host=[my_loginServer]}
    Only the Host field is added to my HttpsURLConnection. The authentication field doesnt appear in standar output. How can i add to my HttpsURLConnection an Authentication field?
    thanks

    I have moved this to the main Dreamweaver forum, as the other forum is intended to deal with the Getting Started video tutorial.
    The best way to get help with layout problems is to upload the files to a website and post the URL in the forum. Someone can then look at the code, and identify the problem. Judging from your description, it sounds as though the Document window is narrow, which would result in the final menu tab dropping down to the next row. Try turning on Live view or previewing the page in a browser. Design view gives only an approximate idea of the final layout. Live view renders the page as it should look in a browser.

  • Help with designing basic class

    Ok, I'm trying to learn java by implementing a Recipe program that I will eventually put up on my web page. My thought was to create a base class called recipe that would essentially be a collection of strings and such. This would then be tied to a database with getFromDatabase() methods etc... However I'm I just want to clarify a few things and make sure I'm headed in the right direction.
    I figure I should create my class something like this:
    public class Recipe
      public String recipeName;
      // more strings like serves source, etc...
      public int rating; // 1-5
      // Ingredient list
      // Category list
      public String directions;
      public Recipe(String recipeName)
      this.recipeName = recipeName;
    }The above is pretty much what I think is right with what I have so far. For the ingredients, I created a special class called ingredient that looks like:
    public class Ingredient
      public String qty;
      public String amt;
      public String desc;
      public Ingredient(String quant, String ammount, String description)
        this.qty = quant;
        this.amt = ammount;
        this.desc = description;
      public Ingredient()
        this.qty = "";
        this.amt = "";
        this.desc = "";
      public String toString()
        String tempstring = new String(this.qty + " " + this.amt + " " + this.desc);
        return tempstring;
    }Then in my recipe class I have:
    public List ingredients = Collections.synchronizedList(new LinkedList());and then I have two overloaded addIngredient methods to add an Ingredient object to this list.
    So am I on the right track? Should I not even bother with a special class just for ingredients?
    Also while I have your attention, if I were to try and get a list of recipes in the database (ie, SELECT recipename FROM recipes;) where should I put this method? Thank you for any help.
    -Chris

    You only use get() and set() methods for data you need to change, I didn't think that I had to point that out.
    The guy is obviously a beginner, there is no need to saturate him with loads of information that isn't too important to him right now; however, it is good to get him used to the get and set methods for the variables that might need changing, and keeping (most of) the variables private (or protected as the case may be).
    Please tell me how setting variables to private does not contribute to information hiding? @_@
    Because, the last time I heard, private variables can't be accessed by other classes.
    Not only that, the get() and set() methods DO hide information, mainly the inner workings of the code. Consider:
    public class Foo {
      private int x;
      public int getX() {
        return x;
      public void setX(int anInt){
        x = anInt;
    public class Bar {
      private Foo mFoo = new Foo();
      public int process(){
        int intialValue = myFoo.getX();
        return initialValue * 4;
    }And say for whatever reason the way Foo handled the way x was stored had to change:
    public class Foo {
      public String x = "0"; // x no longer an int
      public int getX() {
        return Integer.parseInt(x); // convert when needed
      public void setX(int anInt){
        x = new Integer(anInt).toString(); // convert back
    public class Bar {
      private Foo mFoo = new Foo();
      public int process(){
        int intialValue = myFoo.getX(); // none the wiser
        return initialValue * 4;
    }Note, because of the get and set methods, we didn't have to change Bar. I'd say this was a kind of data hiding, no?
    I do know a bit about what I'm saying. I may not be an expert, but what I said was on the wholecorrect, especially considering the OP is a beginner. I never claimed what I told him was the WHOLE of tight encapsulation, but it is a part of it. He doesn't need to know more than what I told him ATM.

  • Need some help with project - help is VERY appreciated!

    This one has been driving me nuts for a few days. So basically, I have this constructor.
    public SportStacker( String newName, int numTimes, int newID )
             name = newName;
             numTimesRecorded = 0;
             times = new double[ numTimes ];
             ID = newID;
          }The important thing here being that it sets ID = newID. That's in the SportStacker class. We also have a method in SportStacker named getID:
    public int getID()
             return ID;
          }Okay, then we have another class, Contestant. In this class, we have an array of SportStacker objects. One method we had to create was to add a new contestant.
    public void addCompetitor(String name, int numTimesRecorded)
             if(numCompetitors == competitors.length)
                increaseSize();
             SportStacker temp = new SportStacker(name, numTimesRecorded, IDtracker);
             competitors[numTimesRecorded] = temp;
             numCompetitors++;
             IDtracker++;
    }Which I think is fine. However, the next one is addCompetitorTimes. It seems like it should be easy, but this part confuses me...in his instructions, he says: "This method should take in two parameters: an int representing the competitors ID and a double representing the time to be recorded. Then, search through competitors for the correct ID using the getID method provided in SportStacker..." This is what confuses me. One of the parameters taken in this method is the int representing his ID, and all getID will do is return what was last used in the constructor. It doesn't make any sense to me! Someone please help!

    johnboy8282 wrote:
    Minus the addTime part, just wanted to make sure I was doing this right first. Thanks so much for the help, your explanation helped me understand a lot!Using a for loop is clearer but yes your on the right track. Minor note, if the competitors array contains nulls then a runtime error will occur due to .getID() applied to a null object. This is easily avoidable.
    public void addCompetitorTimes(int compID, double timeToRecord){
      for(int i=0; i<numCompetitors; i++){
        if(competitors.getID() == compID){
    System.out.print("Add time stuff here...");
    break; //Break from for loop, no need to check other IDs
    }Mel                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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());

  • Help with loading dynamic classes ..need help please

    i'm trying to design a program where by i can load dynamic classes
    the problem i'm getting is that only one class is loading.
    classes are loaded by their names,and index numbers of public methods from a linklist
    .When the program runs only the first class is ever loaded and only the methods of that class ..
    help please
    //class loader
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test2 extends Thread
         public Class c;
         public Class Ray;
         public Class[] x;
         public static Object object = null;
         public Method[] theMethods;
         public static Method[] method,usemethod;
         public int methodcount;
         public static int MethodCt;     
         public static JList list;
    public Method[] startClass(String SetMethodName)
         try
              c = Class.forName(SetMethodName);
              object = c.newInstance();
              theMethods = c.getDeclaredMethods();
              // number of methods
              //methodcount = theMethods.length;
         catch (Exception e)
              e.printStackTrace();
    // return the array then invoke the particular method later
    return theMethods ;
    public void RunMethod(Method[] SomeMethod, int methodcount)
         try
              SomeMethod[methodcount].invoke( object,null );
         catch (Exception e)
              e.printStackTrace();
    // end class loader
    //main calling program
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing .*;
    import java.lang.reflect.*;
    public class JFMenu extends JFrame
         public static JMenu pluginMenu;
         public static JMenuBar bar;
         public static final Test2 w = new Test2();
    public static Method[] setmethod;
    private static ClassLinkList startRef = null;
    private static ClassLinkList linkRef3 = null;
    private static ClassLinkList startRef2 = null;
    private String ClassName,ShortCut;
    private int MethodNumber;
    private JMenuItem PluginItem;
         JFMenu()
              super (" JFluro ");     
              JMenu fileMenu = new JMenu("File");
              fileMenu.setMnemonic('F');
              JMenuItem exitItem = new JMenuItem("Exit");
              exitItem.setMnemonic('X');
              fileMenu.add(exitItem);
              exitItem.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             System.exit(0);
              JMenu pluginMenu = new JMenu("Plugins");
              pluginMenu.setMnemonic('P');
              startRef = new ClassLinkList ("Hello","Hello ",2,1926,"Painter");
              addToList("Foo","Foo ",0,1930,"Author");
              while (startRef.linkRef5 != null)
                   //pluginMenu.addSeparator();
                   ClassName = startRef.linkRef5.className;
                   ShortCut = startRef.linkRef5.shortcutName;
    MethodNumber = startRef.linkRef5.methodNumber;
    AddMenuItem(pluginMenu,ShortCut,ClassName,MethodNumber);
                   startRef.linkRef5 = startRef.linkRef5.next;
              // create menu bar and add JFMenu window to it
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);
              bar.add(pluginMenu);
              //attributes for JFMenu frame
              setSize(500,200);
              setVisible(true);
         }// end JFMenu constructor
         public void AddMenuItem(JMenu MainMenu, String shortcut,String className, final int methodCount )
              if (MainMenu==null)
                   return;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              setmethod = w.startClass(className);
              item.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         public JMenuItem AddMenuItem2(JMenu MainMenu, String shortcut)
              //if (MainMenu==null)
              //     return Main;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              //setmethod = w.startClass(className);
              //item.addActionListener(this);
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         return item;
         public void ReloadMenu(JMenuBar Bar, JMenu PluginMenu)
              if (Bar==null)
                   return;
              //     setJMenuBar(Bar);
              Bar.add(PluginMenu);
              //item.addActionListener(ij);
    public static void main (String args[])
              JFMenu menapp = new JFMenu();
    public static void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description) {
         // Create instance of class ClassLinkList
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);
    // end main calling program
    class Hello extends Thread
    public int getNum()
    System.out.println("I can be ");
    return 5;
    public void rayshowName()
    System.out.println("anything i want ");
    public void rayshowName3()
    System.out.println("to be ");
    class Foo extends Thread
    public int getNum()
    System.out.println("IMHOFF");
    return 5;
    public void rayshowName()
    System.out.println("raYMOND");
    // FAMOUS PERSONS LINKED LIST EXAMPLE
    // Frans Coenen
    // Saturday 15 January 2000
    // Depaertment of Computer Science, University of Liverpool
    class ClassLinkList {
    /* FIELDS */
    public String className;
    public String shortcutName;
    public int methodNumber;
    public int yearOfDeath;
    public String occupation;
    public ClassLinkList next = null;
    public ClassLinkList linkRef5 = this;
    public ClassLinkList startRef = null;
    /* CONSTRUCTORS */
    /* FamousPerson constructor */
    public ClassLinkList(String classname, String shortcutname, int methodnumber, int year2,
                                  String description) {
         className = classname;
         shortcutName = shortcutname;
         methodNumber = methodnumber;
         yearOfDeath = year2;
         occupation = description;
         next = null;
    /* METHODS */
    /* Output famous person linked list */
    public void outputClassLinkedList()
         //public ClassLinkList outputClassLinkedList() {
         ClassLinkList linkRef = this;
         // Loop through linked list till end outputting each record in turn
    while (linkRef != null)
         //System.out.println(linkRef5);
         System.out.println(linkRef.className + ", " + linkRef.shortcutName +
                   " (" + linkRef.methodNumber + "-" + linkRef.methodNumber +
                   "): " + linkRef.occupation);
         linkRef = linkRef.next;     
    //return linkRef;
    //public String ShowCasname()
    //return String ;     
    /* Add a new record to the linked list */
    public ClassLinkList addRecordToLinkedList(ClassLinkList newRef) {
         ClassLinkList tempRef, linkRef;
         // Test if new person is to be added to start of list if so return
    if (newRef.testRecord(this) ) {
         newRef.next = this;
         return(newRef);
         // Loop through remainder of linked list
         tempRef = this;
         linkRef = this.next;
         while (linkRef != null) {
         if (newRef.testRecord(linkRef)) {
         tempRef.next = newRef;
              newRef.next = linkRef;
              return(this);
         tempRef = linkRef;
         linkRef = linkRef.next;
    // Add to end
    tempRef.next = newRef;
         return(this);
    /* Delete a record from the linked list given the first and last name. Four
    posibilities:
    1) Record to be deleted is at front of list
    2) Record to be deleted is at end of list
    3) Record to be deleted is in middle of list
    4) Record not found. */
    public ClassLinkList deleteRecord(String lName, String fName) {
    ClassLinkList tempRef, linkRef;
    // Record at start of list
    if ((this.className == lName) & (this.shortcutName == fName))
         return(this.next);
         // Loop through linked list to discover if record is in middle of list.
         tempRef = this;
    linkRef = this.next;
    while (linkRef != null) {
         if ((linkRef.className == lName) & (linkRef.shortcutName == fName)) {
    tempRef.next = linkRef.next;
    return(this);
    tempRef = linkRef;
    linkRef = linkRef.next;
    // Record at end of list, or not found
    if ((linkRef.className == lName) & (linkRef.shortcutName == fName))
                        linkRef = null;
         else System.out.println("Record: " + lName + " " + fName + " not found!");
         return(this);
    /* TEST METHODS */
    /* Test whether new record comes before existing record or not. If so return
    true, false otherwise. */
    private boolean testRecord(ClassLinkList existingRef) {
         int testResult = className.compareTo(existingRef.className);
         if (testResult < 0) return(true);
         else {
         if ((testResult == 0) & (shortcutName.compareTo(existingRef.shortcutName) < 0 ))
                             return(true);
         // Return false
         return(false);
         public void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description)
         // Create instance of class Famous Person
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);

    I have a similar problem. I am writing a program to read the class names from database and instantiate several classes which extends from ServiceThread (an abstract class extending from Thread).
    rs = pStmt.executeQuery();
    while(rs.next()) {
    String threadclassname = rs.getString("classname").trim();
    try{
    ServiceThread threadinstance = (ServiceThread)Class.forName(threadclassname).newInstance();
    }catch ...
    So far, only the first class is ever instantiated and runs fine. But subsequent classes do not even get pass the "... ... Class.forName(...).newInstance();" line.
    Funny thing is that there are also no exceptions. The JVM just seem to hang there.

  • Please help with correcting calling class and method errors

    Hi All,
    I have created a game (like battleship) for 2 tanks. I can't seem to connect the classes and methods to get the values for the last die face rolled; last direction rolled on a 4 headed dice; the x and y position for each tank; the armour value and the firePower (or hit value) to print.
    Each row of these values is supposed to print 50 times using a while loop.
    (N.B. The code is appended below my name.)
    Could anyone please help me? I would be most grateful. Thank you.
    Steve
    import java.util.*;
    class Client
    static Die die;
    static Direction dir;
    static Tank tk1;
    static Tank tk2;
    public static final
    void main( String[] argv)
    die = new Die();
    dir = new Direction();
    tk1 = new Tank();
    tk2 = new Tank();
    int lastFace;
    int setfaceLast;
    int x;
    int y;
    int armourVal;
    int firePower;
    int battleNum=0;
    int battles;
    int moves = 0;
    System.out.println("Tank");
    System.out.println("'\t' Number");
    System.out.println("'\t' Dir");
    System.out.println("'\t' xValue");
    System.out.println("'\t' yValue");
    System.out.println("'\t' Armour");
    System.out.println("Firepower"+'\n');
    int i=0;
    //int getLastFace();
    //int LastDirName();
    while (i <= 50);
    int XPos;
    int YPos;
    Pos p = new Pos();
    p.setXPos(x);
    p.setYPos(y);
    System.out.println ("'\t' Tank 1-");
    //System.out.println ( die.getLastFace());
    //System.out.println( dir.getLastDirName());
    System.out.println(Pos(x));
    System.out.println(Pos(y));
    System.out.println(armourVal);
    System.out.println(firePower+'\n');
    System.out.println ("Tank 2-");
    System.out.println ( lastFace);
    //System.out.println(LastDir);
    System.out.println(x);
    System.out.println(y);
    System.out.println(armourVal);
    System.out.println(firePower+'\n');
    moves++;
    System.out.println(" '\n' + BATTLE");
    class Tank
    public static final int MINGRID;
    public static final int MAXGRID;
    static Die die = new Die();
    static Direction dir = new Direction();
    private static int battleCount;
    private static int moveCount;
    private int x;
    private int y;
    private int armourVal;
    private int firePower;
    public Tank()
    int MINGRID=-10;
    int MAXGRID=10;
    battleCount=0;
    moveCount=0;
    x=0;
    y=0;
    armourVal=10;
    firePower=1;
    public
    int getmove()
    die.roll();
    dir.roll();
    dir.getLastDir();
    die.getLastFace();
    int x;
    int y;
    int Pos;
    switch( dir.getLastDir() )
    case Direction.UP:
    y += die.getLastFace();
    break;
    case Direction.DOWN:
    y -= die.getLastFace();
    break;
    case Direction.RIGHT:
    x += die.getLastFace();
    case Direction.LEFT:
    x-= die.getLastFace();
    break;
    if ( x > MAXGRID )
    x = (2 * MAXGRID) - x;
    else if ( x < MINGRID )
    x = (-2 * MINGRID) - x;
    if ( y > MAXGRID )
    y = (-2 * MAXGRID) - y;
    else if ( y < MINGRID )
    y = (-2 * MINGRID) - y;
    if ( x == -3 && y == -3 )
    firePower++;
    System.out.println("Yipee - more firepower.");
    if ( x == 3 && y == 3)
    this.armourVal += 10;
    System.out.println("Yipee - more armour.");
    return Pos;
    //printDetails();
    public boolean getcontinueBattle(Tank tk2)
    moveCount++;
    if ( x == tk2.x && y == tk2.y)
    battleCount++;
    System.out.println("Battle");
    tk2.armourVal -= firePower;
    armourVal -= tk2.firePower;
    if (tk2.armourVal < 0 )
    int moveCount, battleCount;
    return false;
    if ( armourVal < 0 )
    int moveCount, battleCount;
    return false;
    return true;
    public int getprintDetails()
    int ptDet;
    return ptDet;
    class Direction
    private int lastFaceDir;
    private Random rnd;
    public static final int UP = 1;
    public static final int DOWN = 2;
    public static final int LEFT = 3;
    public static final int RIGHT = 4;
    String direction;
    private
    int getRandomNum()
    int raw = rnd.nextInt();
    raw = Math.abs( raw );
    raw %= 4;
    raw++;
    return raw;
    public
    Direction()
    rnd = new Random();
    roll();
    public
    int roll()
    lastFaceDir = getRandomNum();
    if (lastFaceDir == UP)
    direction = "up";
    else if (lastFaceDir == DOWN)
    direction= "down";
    else if (lastFaceDir == LEFT)
    direction = "left";
    else if (lastFaceDir == RIGHT)
    direction= "right";
    return lastFaceDir;
    public
    int getLastFaceDir()
    return lastFaceDir;
    }// end class
    class Die
    private int lastFace;
    private Random rnd;
    private
    int getRandomNum()
    int raw = rnd.nextInt();
    raw = Math.abs( raw );
    raw %= 6;
    raw++;
    return raw;
    public
    Die()
    rnd = new Random();
    roll();
    public
    int roll()
    lastFace = getRandomNum();
    return lastFace;
    public
    int getLastFace()
    return lastFace;
    }// end class

    I got this sorted!
    I unzipped the JAR and loaded the classes individually - so now the "reference" issue went away. Instead I now have a new problem, but I will post that seperately.

  • Need HELP with objects and classes problem (program compiles)

    Alright guys, it is a homework problem but I have definitely put in the work. I believe I have everything right except for the toString method in my Line class. The program compiles and runs but I am not getting the right outcome and I am missing parts. I will post my problems after the code. I will post the assignment (sorry, its long) also. If anyone could help I would appreciate it. It is due on Monday so I am strapped for time.
    Assignment:
    -There are two ways to uniquely determine a line represented by the equation y=ax+b, where a is the slope and b is the yIntercept.
    a)two diffrent points
    b)a point and a slope
    !!!write a program that consists of three classes:
    1)Point class: all data MUST be private
    a)MUST contain the following methods:
    a1)public Point(double x, double y)
    a2)public double x ()
    a3public double y ()
    a4)public String toString () : that returns the point in the format "(x,y)"
    2)Line class: all data MUST be private
    b)MUST contain the following methods:
    b1)public Line (Point point1, Point point2)
    b2)public Line (Point point1, double slope)
    b3)public String toString() : that returns the a text description for the line is y=ax+b format
    3)Point2Line class
    c1)reads the coordinates of a point and a slope and displays the line equation
    c2)reads the coordinates of another point (if the same points, prompt the user to change points) and displays the line equation
    ***I will worry about the user input later, right now I am using set coordinates
    What is expected when the program is ran: example
    please input x coordinate of the 1st point: 5
    please input y coordinate of the 1st point: -4
    please input slope: -2
    the equation of the 1st line is: y = -2.0x+6.0
    please input x coordinate of the 2nd point: 5
    please input y coordinate of the 2nd point: -4
    it needs to be a diffrent point from (5.0,-4.0)
    please input x coordinate of the 2nd point: -1
    please input y coordinate of the 2nd point: 2
    the equation of the 2nd line is: y = -1.0x +1.0
    CODE::
    public class Point{
         private double x = 0;
         private double y = 0;
         public Point(){
         public Point(double x, double y){
              this.x = x;
              this.y = y;
         public double getX(){
              return x;
         public double setX(){
              return this.x;
         public double getY(){
              return y;
         public double setY(){
              return this.y;
         public String toString(){
              return "The point is " + this.x + ", " + this.y;
    public class Line
         private double x = 0;
         private double y = 0;
         private double m = 0;
         private double x2 = 0;
         private double y2 = 0;
         public Line()
         public Line (Point point1, Point point2)
              this.x = point1.getX();
              this.y = point1.getY();
              this.x2 = point2.getX();
              this.y2 = point2.getY();
              this.m = slope(point1, point2);
         public Line (Point point1, double slope)
              this.x = point1.getX();
              this.y = point1.getY();
         public double slope(Point point1, Point point2)//finds slope
              double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
              return m1;
         public String toString()
              double temp = this.x- this.x2;
              return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
              //y-y1=m(x-x1)
    public class Point2Line
         public static void main(String[]args)
              Point p = new Point(3, -3);
              Point x = new Point(10, 7);
              Line l = new Line(p, x);
              System.out.println(l.toString());
    }My problems:
    I dont have the right outcome due to I don't know how to set up the toString in the Line class.
    I don't know where to put if statements for if the points are the same and you need to prompt the user to put in a different 2nd point
    I don't know where to put in if statements for the special cases such as if the line the user puts in is a horizontal or vertical line (such as x=4.7 or y=3.4)
    Edited by: ta.barber on Apr 20, 2008 9:44 AM
    Edited by: ta.barber on Apr 20, 2008 9:46 AM
    Edited by: ta.barber on Apr 20, 2008 10:04 AM

    Sorry guys, I was just trying to be thorough with the assignment. Its not that if the number is valid, its that you cannot put in the same coordinated twice.
    public class Line
         private double x = 0;
         private double y = 0;
         private double m = 0;
         private double x2 = 0;
         private double y2 = 0;
         public Line()
         public Line (Point point1, Point point2)
              this.x = point1.getX();
              this.y = point1.getY();
              this.x2 = point2.getX();
              this.y2 = point2.getY();
              this.m = slope(point1, point2);
         public Line (Point point1, double slope)
              this.x = point1.getX();
              this.y = point1.getY();
         public double slope(Point point1, Point point2)//finds slope
              double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
              return m1;
         public String toString()
              double temp = this.x- this.x2;
              return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
              //y-y1=m(x-x1)
    public class Point2Line
         public static void main(String[]args)
              Point p = new Point(3, -3);
              Point x = new Point(10, 7);
              Line l = new Line(p, x);
              System.out.println(l.toString());
    }The problem is in these lines of code.
    public double slope(Point point1, Point point2) //if this method finds the slope than how would i use the the two coordinates plus "m1" to
              double m1 = (point1.getY() - point2.getY())/(point1.getX() - point2.getX());
              return m1;
         public String toString()
              double temp = this.x- this.x2;
              return this.y + " = " +temp + "" + "(" + this.m + ")" + " " + "+ " + this.y2;
              //y-y1=m(x-x1)
         }if slope method finds the slope than how would i use the the two coordinates + "m1" to create a the line in toString?

  • Need help with assignment for class. its for my high school project :(

    i really need help, my problem is that with my code i cannot get the "previous", "done" and "next" buttons to work.they cannot seem to find the items from each other. so could someone look at those buttons in the code and tell me how to fix please? the code is as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GradeCalculator extends JFrame {
         private JTextField gradeA = new JTextField(3);
         private JTextField gradeB = new JTextField(3);
         private JTextField gradeC = new JTextField(3);
         private JTextField gradeD = new JTextField(3);
         private JTextField gradeE = new JTextField(3);
         private JTextField studentsName = new JTextField(15);
         private JTextField assignmentOne = new JTextField(5);
         private JTextField assignmentTwo = new JTextField(5);
         private JTextField assignmentThree = new JTextField(5);
         private JTextField examOne = new JTextField(5);
         private JTextField examTwo = new JTextField(5);
         private JTextArea textOutput;
         private JPanel buttonJPanel;
         public GradeCalculator(){
              JMenu fileMenu = new JMenu("File");
              JMenuItem aboutItem = new JMenuItem( "About" );
    fileMenu.add( aboutItem );
    aboutItem.addActionListener(
    new ActionListener()
    public void actionPerformed( ActionEvent event )
    JOptionPane.showMessageDialog( GradeCalculator.this,
    "Grade Calculator Version 1.00. \nMade by Carlson Smith.\nSchool: Pre-University\nSubject: Cape Computer Science.",
    "About", JOptionPane.PLAIN_MESSAGE );
              JMenuItem exitItem = new JMenuItem( "Exit" );
    fileMenu.add( exitItem );
    exitItem.addActionListener(
    new ActionListener()
    public void actionPerformed( ActionEvent event )
    System.exit( 0 );
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);     
              JTabbedPane tabbedPane = new JTabbedPane();
              buttonJPanel = new JPanel();
              buttonJPanel.setLayout(new GridLayout(1,2));
              JButton ok = new JButton("OK");
              ok.addActionListener(new OkBtnListener());
              JButton edit = new JButton("EDIT");
              edit.addActionListener(new EditBtnListener());
              /**JButton previous = new JButton("PREVIOUS");
              previous.addActionListener(new PreviousBtnListener());
              JButton done = new JButton("DONE");
              done.addActionListener(new DoneBtnListener());
              JButton next = new JButton("NEXT");
              next.addActionListener(new NextBtnListener());
              JPanel contentPane = new JPanel();
              contentPane.setLayout(new FlowLayout());
              contentPane.add(new JLabel("Grade A")/**,BorderLayout.NORTH*/);
              contentPane.add(gradeA/**,BorderLayout.NORTH*/);
              contentPane.add(new JLabel("Grade B")/**,BorderLayout.WEST*/);
              contentPane.add(gradeB/**,BorderLayout.WEST*/);
              contentPane.add(new JLabel("Grade C")/**,BorderLayout.WEST*/);
              contentPane.add(gradeC/**,BorderLayout.WEST*/);
              contentPane.add(new JLabel("Grade D")/**,BorderLayout.WEST*/);
              contentPane.add(gradeD/**,BorderLayout.WEST*/);
              contentPane.add(new JLabel("Grade E")/**,BorderLayout.WEST*/);
              contentPane.add(gradeE/**,BorderLayout.WEST*/);
              tabbedPane.addTab("Grade Entry Tab", null, contentPane, "Grade Tab");
              //contentPane.add(ok,BorderLayout.WEST);
              //contentPane.add(edit,BorderLayout.WEST);
              buttonJPanel.add(ok);
              buttonJPanel.add(edit);
              contentPane.add(buttonJPanel, BorderLayout.WEST);
              JPanel content = new JPanel();
              content.setLayout(new FlowLayout());
              content.add(new JLabel("Student's Name")/**,BorderLayout.EAST*/);
              content.add(studentsName/**,BorderLayout.EAST*/);
              content.add(new JLabel("Assignment 1 score:")/**,BorderLayout.EAST*/);
              content.add(assignmentOne/**,BorderLayout.EAST*/);
              content.add(new JLabel("Assignment 2 score:")/**,BorderLayout.EAST*/);
              content.add(assignmentTwo/**,BorderLayout.EAST*/);
              content.add(new JLabel("Assignment 3 score:")/**,BorderLayout.EAST*/);
              content.add(assignmentThree/**,BorderLayout.EAST*/);
              content.add(new JLabel("Exam 1 score:")/**,BorderLayout.EAST*/);
              content.add(examOne/**,BorderLayout.EAST*/);
              content.add(new JLabel("Exam 2 score:")/**,BorderLayout.EAST*/);
              content.add(examTwo/**,BorderLayout.EAST*/);
              //content.add(previous,BorderLayout.EAST);
              //content.add(done,BorderLayout.EAST);
              //content.add(next,BorderLayout.EAST);
              Box box = Box.createVerticalBox();
              String output = "test";
              String outputTwo = output;
              textOutput = new JTextArea(outputTwo,10,30);
              box.add(new JScrollPane(textOutput));
              textOutput.setEditable(false);
              content.add(box,BorderLayout.SOUTH);
              tabbedPane.addTab("Calculator Tab", null, content, "Calculation & Output Tab");
              setContentPane(tabbedPane);
              pack();
              setTitle("Grade Calculator");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              class OkBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        String gradeAA = gradeA.getText();
                        double gradA = Double.parseDouble(gradeAA);
                        gradeA.setText(" "+gradA);
                        String gradeBB = gradeB.getText();
                        double gradB = Double.parseDouble(gradeBB);
                        gradeB.setText(" "+gradB);
                        String gradeCC = gradeC.getText();
                        double gradC = Double.parseDouble(gradeCC);
                        gradeC.setText(" "+gradC);
                        String gradeDD = gradeD.getText();
                        double gradD = Double.parseDouble(gradeDD);
                        gradeD.setText(" "+gradD);
                        String gradeEE = gradeE.getText();
                        double gradE = Double.parseDouble(gradeEE);
                        gradeE.setText(" "+gradE);
                        gradeA.setEditable(false);
                        gradeB.setEditable(false);
                        gradeC.setEditable(false);
                        gradeD.setEditable(false);
                        gradeE.setEditable(false);
              class EditBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        gradeA.setEditable(true);
                        gradeB.setEditable(true);
                        gradeC.setEditable(true);
                        gradeD.setEditable(true);
                        gradeE.setEditable(true);
              /**class PreviousBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        if (i <= 0){
                             i = 0;
                        }else if(i > 0){
                             i = i-1;
              class DoneBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        output = "Results \n";
                        output+= studentName[i]+" Assignment Average = "+averageO[i]+" Exam Average = "+averageT[i]+" Overall average = ";
                        output+= tAverage[i]+" Letter Grade = "+letterGrade;
              class NextBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        String [] studentName = new String [40];
                        double [] assignOne = new double [40];
                        double [] assignTwo = new double [40];
                        double [] assignThree = new double [40];
                        double [] gradeOne = new double [40];
                        double [] gradeTwo = new double [40];
                        double [] averageO = new double [40];
                        double [] averageT = new double [40];
                        double [] tAverage = new double [40];
                        char [] letterGrade = new char [40];
                        double max = 0;
                        double min = 100;
                        int i = 0;
                        while(i < studentName.length){
                             studentName[i] = studentsName.getText();
                             studentsName.setText(studentName[i]);
                             String aOne = assignmentOne.getText();
                             assignOne[i] = Double.parseDouble(aOne);
                             assignmentOne.setText(assignOne[i]);
                             String aTwo = assignmentTwo.getText();
                             assignTwo[i] = Double.parseDouble(aTwo);
                             assignmentTwo.setText(assignTwo[i]);
                             String aThree = assignmentThree.getText();
                             assignThree[i] = Double.parseDouble(aThree);
                             assignmentThree.setText(assignThree[i]);
                             String gOne = examOne.getText();
                             gradeOne[i] = Double.parseDouble(gOne);
                             examOne.setText(gradeOne[i]);
                             String gTwo = examTwo.getText();
                             gradeTwo = Double.parseDouble(gTwo);
                             examTwo.setText(gradeTwo[i]);
                             averageO[i] = (assignOne[i]+assignTwo[i]+assignThree[i])/3;
                             averageT[i] = (gradeOne[i]+gradeTwo[i])/2;
                             tAverage[i] = (averageO[i]+averageT[i])/2;
                             if (tAverage[i] >= gradeA){
                                  letterGrade[i] = 'A';
                             }else if(tAverage[i] >= gradeB){
                                  letterGrade[i] = 'B';
                             }else if(tAverage[i] >= gradeC){
                                  letterGrade[i] = 'C';
                             }else if(tAverage[i] >= gradeD){
                                  letterGrade[i] = 'D';
                             }else if(tAverage[i] <= gradeE){
                                  letterGrade[i] = 'E';
              public static void main(String[]args){
                   GradeCalculator calWindow = new GradeCalculator();
                   calWindow.setVisible(true);

    i have to apologize to jittei for the misunderstand i do not know which defination of terms is for which line of code but i know what they do, to solve the problem i have actually made another class in the workspace file called students and now all the bottons work, all i have to do now is properly arrange and put in some additional lines of code and it will be completed. teacher gave me the idea of putting in a new class to help in calling codes from other subclasses in the main program. ah well guess non of you could think of that thanks for the help-ish and hope yall will atleast try to be nice to new people that come in the room. the new coding is:
    of course all the commented out lines are not being used in the program anymore but just there till i have the program working with everything in it runs and performs the actions required now though ^_^
    *Group CAPE Computer Science 2007/8
    *GradeCalculator.java
    *@author Carlson Smith
    *@version 3.01          07/02/2008
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GradeCalculator extends JFrame {
         private JTextField gradeA = new JTextField(3);
         private JTextField gradeB = new JTextField(3);
         private JTextField gradeC = new JTextField(3);
         private JTextField gradeD = new JTextField(3);
         private JTextField gradeE = new JTextField(3);
         private JTextField studentsName = new JTextField(15);
         private JTextField assignmentOne = new JTextField(5);
         private JTextField assignmentTwo = new JTextField(5);
         private JTextField assignmentThree = new JTextField(5);
         private JTextField examOne = new JTextField(5);
         private JTextField examTwo = new JTextField(5);
         private JTextArea  textOutput;
         private JPanel buttonJPanel;
         private JPanel buttonJPanelTwo;
         private Student [] students = new Student[40];
         private int current = 0;
         private String output;
         public GradeCalculator(){
              JMenu fileMenu = new JMenu("File");
              JMenuItem aboutItem = new JMenuItem( "About" );
              for (int i=0;i<40;i++){
                   students[i] = new Student("");
            fileMenu.add( aboutItem );
            aboutItem.addActionListener(
               new ActionListener()
                  public void actionPerformed( ActionEvent event )
                     JOptionPane.showMessageDialog( GradeCalculator.this,
                        "Grade Calculator Version 1.00. \nMade by Carlson Smith.\nSchool: Pre-University\nSubject: Cape Computer Science.",
                        "About", JOptionPane.PLAIN_MESSAGE );
              JMenuItem exitItem = new JMenuItem( "Exit" ); 
            fileMenu.add( exitItem );
            exitItem.addActionListener(
               new ActionListener()
                  public void actionPerformed( ActionEvent event )
                     System.exit( 0 );
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);     
              JTabbedPane tabbedPane = new JTabbedPane();
              buttonJPanel = new JPanel();
              buttonJPanel.setLayout(new GridLayout(1,2));
              JButton ok = new JButton("OK");
              ok.addActionListener(new OkBtnListener());
              JButton edit = new JButton("EDIT");
              edit.addActionListener(new EditBtnListener());
              buttonJPanelTwo = new JPanel();
              buttonJPanelTwo.setLayout(new GridLayout(1,3));
              JButton previous = new JButton("PREVIOUS");
              previous.addActionListener(new PreviousBtnListener());
              JButton done = new JButton("DONE");
              done.addActionListener(new DoneBtnListener());
              JButton next = new JButton("NEXT");
              next.addActionListener(new NextBtnListener());
              JPanel contentPane = new JPanel();
              contentPane.setLayout(new FlowLayout());
              contentPane.add(new JLabel("Grade A")/**,BorderLayout.NORTH*/);
              contentPane.add(gradeA/**,BorderLayout.NORTH*/);
              contentPane.add(new JLabel("Grade B")/**,BorderLayout.WEST*/);
              contentPane.add(gradeB/**,BorderLayout.WEST*/);
              contentPane.add(new JLabel("Grade C")/**,BorderLayout.WEST*/);
              contentPane.add(gradeC/**,BorderLayout.WEST*/);
              contentPane.add(new JLabel("Grade D")/**,BorderLayout.WEST*/);
              contentPane.add(gradeD/**,BorderLayout.WEST*/);
              contentPane.add(new JLabel("Grade E")/**,BorderLayout.WEST*/);
              contentPane.add(gradeE/**,BorderLayout.WEST*/);
              tabbedPane.addTab("Grade Entry Tab", null, contentPane, "Grade Tab");
              //contentPane.add(ok,BorderLayout.WEST);
              //contentPane.add(edit,BorderLayout.WEST);
              buttonJPanel.add(ok);
              buttonJPanel.add(edit);
              contentPane.add(buttonJPanel, BorderLayout.WEST);
              JPanel content = new JPanel();
              content.setLayout(new FlowLayout());
              content.add(new JLabel("Student's Name")/**,BorderLayout.EAST*/);
              content.add(studentsName/**,BorderLayout.EAST*/);
              content.add(new JLabel("Assignment 1 score:")/**,BorderLayout.EAST*/);
              content.add(assignmentOne/**,BorderLayout.EAST*/);
              content.add(new JLabel("Assignment 2 score:")/**,BorderLayout.EAST*/);
              content.add(assignmentTwo/**,BorderLayout.EAST*/);
              content.add(new JLabel("Assignment 3 score:")/**,BorderLayout.EAST*/);
              content.add(assignmentThree/**,BorderLayout.EAST*/);
              content.add(new JLabel("Exam 1 score:")/**,BorderLayout.EAST*/);
              content.add(examOne/**,BorderLayout.EAST*/);
              content.add(new JLabel("Exam 2 score:")/**,BorderLayout.EAST*/);
              content.add(examTwo/**,BorderLayout.EAST*/);
              //content.add(previous,BorderLayout.EAST);
              //content.add(done,BorderLayout.EAST);
              //content.add(next,BorderLayout.EAST);
              buttonJPanelTwo.add(previous);
              buttonJPanelTwo.add(done);
              buttonJPanelTwo.add(next);
              content.add(buttonJPanelTwo, BorderLayout.EAST);
              Box box = Box.createVerticalBox();
              //String outputTwo = output;
              //textOutput.setText(output);
              textOutput = new JTextArea(output,10,30);
              box.add(new JScrollPane(textOutput));
              //textOutput.setEditable(true);
              content.add(box,BorderLayout.SOUTH);
              tabbedPane.addTab("Calculator Tab", null, content, "Calculation & Output Tab");
              setContentPane(tabbedPane);
              pack();
              setTitle("Grade Calculator");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              class OkBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        String gradeAA = gradeA.getText();
                        double gradA = Double.parseDouble(gradeAA);
                        gradeA.setText(" "+gradA);
                        String gradeBB = gradeB.getText();
                        double gradB = Double.parseDouble(gradeBB);
                        gradeB.setText(" "+gradB);
                        String gradeCC = gradeC.getText();
                        double gradC = Double.parseDouble(gradeCC);
                        gradeC.setText(" "+gradC);
                        String gradeDD = gradeD.getText();
                        double gradD = Double.parseDouble(gradeDD);
                        gradeD.setText(" "+gradD);
                        String gradeEE = gradeE.getText();
                        double gradE = Double.parseDouble(gradeEE);
                        gradeE.setText(" "+gradE);
                        gradeA.setEditable(false);
                        gradeB.setEditable(false);
                        gradeC.setEditable(false);
                        gradeD.setEditable(false);
                        gradeE.setEditable(false);
              class EditBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        gradeA.setEditable(true);
                        gradeB.setEditable(true);
                        gradeC.setEditable(true);
                        gradeD.setEditable(true);
                        gradeE.setEditable(true);
              class PreviousBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        Student currentStudent = students[current];
                        currentStudent.setStudentName(studentsName.getText());          
                        currentStudent.setAssignOne(Double.parseDouble(assignmentOne.getText()));
                        currentStudent.setAssignTwo(Double.parseDouble(assignmentTwo.getText()));
                        currentStudent.setAssignThree(Double.parseDouble(assignmentThree.getText()));
                        currentStudent.setExamOneGrade(Double.parseDouble(examOne.getText()));
                        currentStudent.setExamTwoGrade(Double.parseDouble(examTwo.getText()));
                        currentStudent = students[current];
                        if (current <= 0){
                             current = 0;
                        }else if(current > 0){
                             current = current-1;
                        refresh();               
                        System.out.println(current);
              class DoneBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
                        Student currentStudent = students[current];
                        //output = "Result \n";
                        output = currentStudent.getStudentName()+". Assignment Average = "+currentStudent.getAverage()+". Exam Average = "+currentStudent.getExamAverage()+". Overall average = ";
                        output+= currentStudent.getTotalAverage()/**+" Letter Grade = "+letterGrade[current]*/;
                        textOutput.setText(output);
                        System.out.println(output);
                        currentStudent = students[current];
              class NextBtnListener implements ActionListener{
                   public void actionPerformed(ActionEvent e){
    //                    String [] studentName = new String [40];
    //                    double [] assignOne = new double [40];
    //                    double [] assignTwo = new double [40];
    //                    double [] assignThree = new double [40];
    //                    double [] gradeOne = new double [40];
    //                    double [] gradeTwo = new double [40];
    //                    double [] averageO = new double [40];
    //                    double [] averageT = new double [40];
    //                    double [] tAverage = new double [40];
    //                    char [] letterGrade = new char [40];
                        //double max = 0;
                        //double min = 100;
                        Student currentStudent = students[current];
                        currentStudent.setStudentName(studentsName.getText());
                        currentStudent.setAssignOne(Double.parseDouble(assignmentOne.getText()));
                        currentStudent.setAssignTwo(Double.parseDouble(assignmentTwo.getText()));
                        currentStudent.setAssignThree(Double.parseDouble(assignmentThree.getText()));
                        currentStudent.setExamOneGrade(Double.parseDouble(examOne.getText()));
                        currentStudent.setExamTwoGrade(Double.parseDouble(examTwo.getText()));
    //                    currentStudent = students[current];
                        current++;
                        refresh();
    /**                    while(i < studentName.length){
                             String aOne = assignmentOne.getText();
                             assignOne[i] = Double.parseDouble(aOne);
                             assignmentOne.setText(" "+assignOne);
                             String aTwo = assignmentTwo.getText();
                             assignTwo[i] = Double.parseDouble(aTwo);
                             assignmentTwo.setText(" "+assignTwo[i]);
                             String aThree = assignmentThree.getText();
                             assignThree[i] = Double.parseDouble(aThree);
                             assignmentThree.setText(" "+assignThree[i]);
                             String gOne = examOne.getText();
                             gradeOne[i] = Double.parseDouble(gOne);
                             examOne.setText(" "+gradeOne[i]);
                             String gTwo = examTwo.getText();
                             gradeTwo[i] = Double.parseDouble(gTwo);
                             examTwo.setText(" "+gradeTwo[i]);
                             averageO[i] = (assignOne[i]+assignTwo[i]+assignThree[i])/3;
                             averageT[i] = (gradeOne[i]+gradeTwo[i])/2;
                             tAverage[i] = (averageO[i]+averageT[i])/2;
                             if (tAverage[i] >= Double.parseDouble(gradeA.getText())){
                                  letterGrade[i] = 'A';
                             }else if(tAverage[i] >= Double.parseDouble(gradeB.getText())){
                                  letterGrade[i] = 'B';
                             }else if(tAverage[i] >= Double.parseDouble(gradeC.getText())){
                                  letterGrade[i] = 'C';
                             }else if(tAverage[i] >= Double.parseDouble(gradeD.getText())){
                                  letterGrade[i] = 'D';
                             }else if(tAverage[i] <= Double.parseDouble(gradeE.getText())){
                                  letterGrade[i] = 'E';
              public void refresh(){
                   Student currentStudent = students[current];
                   studentsName.setText(currentStudent.getStudentName());
                   assignmentOne.setText(currentStudent.getAssignOne()+"");
                   assignmentTwo.setText(currentStudent.getAssignTwo()+"");
                   assignmentThree.setText(currentStudent.getAssignThree()+"");
                   examOne.setText(currentStudent.getExamOneGrade()+"");
                   examTwo.setText(currentStudent.getExamTwoGrade()+"");
              public static void main(String[]args){
                   GradeCalculator calWindow = new GradeCalculator();
                   calWindow.setVisible(true);
    Second class implemented./**
    *Group CAPE Computer Science 2007/8
    *Student.java
    *@author Carlson Smith
    *@version 3.01          07/02/2008
    public class Student {
         private String studentName;
         private double assignOne;
         private double assignTwo;
         private double assignThree;
         private double examOneGrade;
         private double examTwoGrade;
         public Student(String sName){
              studentName = sName;     
         public String getStudentName(){
              return studentName;
         public double getAssignOne(){
              return assignOne;
         public double getAssignTwo(){
              return assignTwo;
         public double getAssignThree(){
              return assignThree;
         public double getExamOneGrade(){
              return examOneGrade;
         public double getExamTwoGrade(){
              return examTwoGrade;
         public void setStudentName(String sName){
              studentName = sName;
         public void setAssignOne(double assignOne){
              this.assignOne = assignOne;
         public void setAssignTwo(double assignTwo){
              this.assignTwo = assignTwo;
         public void setAssignThree(double assignThree){
              this.assignThree = assignThree;
         public void setExamOneGrade(double examOneGrade){
              this.examOneGrade = examOneGrade;
         public void setExamTwoGrade(double examTwoGrade){
              this.examTwoGrade = examTwoGrade;
         public double getAverage(){
              return (assignOne + assignTwo + assignThree)/3;
         public double getExamAverage(){
              return (examOneGrade + examTwoGrade)/2;
         public double getTotalAverage(){
              return (getAverage() + getExamAverage())/2;
    this thread can be closed now. l8rz :P
    Edited by: Jacal on Feb 10, 2008 7:28 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

  • Need help with User defined class

    I need to create two Java classes. The first class will be used as a template for objects which represent students, the second will be a program which creates two student object and calls some of their methods.
    Create a file called "Student.java" and in it definr a class called Student which has the following Attributes:
    * a String variable which can hold the student's name
    * a double variable which can hold the studnet's exam mark.
    In the student class, define public methods as follows:
    1 a constructor method which accepts no arguments. This method should initialise the student's name to "unknown" and set the examination mark to zero
    2 A constructor method which accepts 2 arguments- the first being a string representing the student's name and the other being a double which represents their exam mark. These arguments should be used to initialise the state variables with one proviso- the exam mark must not be set to a number outside the range 0...100. If the double argument is outside this range,set the exam mark attribute to 0.
    3 A reader method which returns the students name
    4 A reader method which returns the students exam mark.
    5 A writer method which sets the student's name
    6 A writer method which sets the student's eeam mark. If the exam mark argument is outside the the 0...100 range,the exam mark attibute should not be modified.
    7 A method which returns the studnet's grade. The grade is a string such as "HD" or "FL" which can be determined from the following table.
    Grade Exam Mark
    HD 85..100
    DI 75..84
    CR 65..74
    PS 50..64
    FL 0..49
    Part2 Client Code
    Write a program in a file called "TestStudent.java"
    Make sure the file is in the same directory as tne "Student.java" file
    In the main method of "TestStudent.java" write code to do each of the following tasks
    1 Create a student object using the no argument constructor.
    2 Print this student's name and their exam mark
    3 Create another student object using the other constructor-supply your own name as the string argument and whatever exam mark you like as the double argument
    4 Print this studnet's name and their exam mark
    5 Change the exam mark of this student to 50 and print their exam mark and grade.
    6 Change the examination mark of this studnet to 256 and print their exam mark and grade.
    Can someone please help
    goober

    Sorry, I have sent you the wrong version. Try this,
    public class Student {
         private String name;
         private double examMark;
         public Student() {
              name = "unknown";
              examMark = 0.0;
         public Student(String n, double em) {
              name = n;
              if(em >0 && em < 100) {
                   examMark = em;
              } else {
                   examMark = 0.0;
         public String getName() {
              return name;
         public void setName(String n) {
              name = n;
         public double getExamMark() {
              return examMark;
         public void setExamMark(double em) {
              if(em >0 && em < 100) {
                   examMark = em;
              } else {
                   examMark = 0.0;
         public String getGrade() {
              if ( examMark > 84) return "HD";
              else if(examMark > 74) return "DI";
              else if(examMark > 64) return "CR";
              else if(examMark > 49) return "PS";
              else return "FL";
    } and
    class TestStudent {
         public static void main(String a[]) {
              Student st = new Student();
              System.out.println("Student Name is : "+st.getName());
              System.out.println("Student Marks is : "+st.getExamMark());
              Student st1 = new Student("XXXX",78);
              System.out.println("Student Name is : "+st1.getName());
              System.out.println("Student Marks is : "+st1.getExamMark());
              st1.setExamMark(67);
              System.out.println("Student Marks is : "+st1.getExamMark());
              System.out.println("Student Grade is : "+st1.getGrade());
              st1.setExamMark(256);
              System.out.println("Student Marks is : "+st1.getExamMark());
              System.out.println("Student Grade is : "+st1.getGrade());
    }Hope this helps.
    Sudha

  • Help with using Scanner Class

    Hi there - I'm a newbie to Java and may have posted this in the wrong forum previously.
    I am trying to modify a program so instead of using a BufferReader, a scanner class will be used. It is basically a program to read in a name and then display the variable in a line of text.
    Being new to Java and a weak programmer, I am getting in a mess with this and missing something somewhere. I don't think I'm using scanner in the correct way.
    Any help or pointers would be good. There are 2 programs of code being used. 'Sample' and 'Run Sample'
    Thanks in advance.
    Firstly, this program will run named 'Sample'
    <code>
    * Sample.java
    * Class description and usage here.
    * Created on 15 October 2006
    package internetics;
    * @author John
    * @version 1.2
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    // import com.ralph.*;
    public class Sample extends JFrame
    implements java.awt.event.ActionListener{
    private JButton jButton1; // this button is for pressing
    private JLabel jLabel1;
    private String name;
    /** Creates new object ChooseFile */
    public Sample() {
    initComponents();
    name = "";
    selectInput();
    public Sample(String name) {
    this();
    this.name = name;
    private void initComponents() {
    Color bright = Color.red;
    jButton1 = new JButton();
    jLabel1= new JLabel();
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    exitForm(evt);
    getContentPane().setLayout(new java.awt.GridLayout(2, 1));
    jButton1.setBackground(Color.white);
    jButton1.setFont(new Font("Verdana", 1, 12));
    jButton1.setForeground(bright);
    jButton1.setText("Click Me!");
    jButton1.addActionListener(this);
    jLabel1.setFont(new Font("Verdana", 1, 18));
    jLabel1.setText("05975575");
    jLabel1.setOpaque(true);
    getContentPane().add(jButton1);
    getContentPane().add(jLabel1);
    pack();
    public void actionPerformed(ActionEvent evt) {
    System.out.print("Talk to me " name " : ");
    try {
    jLabel1.setText(input.readLine());
    } catch (IOException ioe) {
    jLabel1.setText("Ow! You pushed my button");
    System.err.println("IO Error: " + ioe);
    /** Exit this Application */
    private void exitForm(WindowEvent evt) {
    System.exit(0);
    /** Initialise and Scan input Stream */
    private void selectInput() {
    input = new Scanner(new InputStreamReader(System.in));
    /**int i = sc.nextInt(); */
    /** Getter for name prompt */
    public String getName() {
    return name;
    /** Setter for name prompt */
    public void setName(String name) {
    this.name = name;
    * @param args the command line arguments
    public static void main(String args[]) {
    new Sample("John").show();
    </code>
    and this is the second program called 'RunSample will run.
    <code>
    class RunSample {
    public static void main(String args[]) {
    new internetics.Sample("John").show();
    </code>

    The compiler I'm using is showing errors in these areas of the code. I've read the tutorials and still can't get it. They syntax for the scanner must be in the wrong format??
    the input.readLine appears incorrect below.
      public void actionPerformed(ActionEvent evt) {
        System.out.print("Talk to me " +name+ " : ");
        try {
            jLabel1.setText(input.readLine());
        } catch (IOException ioe) {
          jLabel1.setText("Ow! You pushed my button");
          System.err.println("IO Error: " + ioe);
        }and also here...
    the input is showing errors
      /** Initialise and Scan input Stream */
      private void selectInput() {
        input = new Scanner(new InputStreamReader(System.in));
       /**int i = sc.nextInt(); */
      }Thanks

  • Please help with CS5 "Help" problems

    I installed Photoshop (V12.0) and Dreamweaver CS5 yesterday  -  8G Memory  Win 7 Pro 64 bit with Kaspersky 2011 IS which I disable during downloads
    I cannot access "Help" in either - I get the message "... cannot find Adobe Air - please download from adobe.com/go/getair"
    I've attempted this many times but get the message Air already installed but, I cannot find AIr anywhere in the Registry. I've also failed to install thedownloaded  upgrade to Photoshop 12.0.1. I seem to have downloaded Adobe Flash OK.
    I've gone almost mad trying to get to the point where I could actually post to this forum, hope next time the journey here will be shorter.
    Would be grateful for any help and thanks for past help
    warmest regards
    grifd

    Adobe AIR normally appears at or near the top of your Programs and Features list (within the Control Panel).  I take it it's not there for you?
    Did you try to install the Photoshop 12.0.1 update directly from Adobe's installer, or did you fail the automatic update?  If the latter, try this link:
    http://www.adobe.com/support/downloads/detail.jsp?ftpID=4733
    (which is referenced from)
    http://www.adobe.com/support/downloads/product.jsp?product=39&platform=Windows
    -Noel

  • Help with the Date class

    I have researched the documentation for this class, and find three constructors. One that is deprecated, one that creates a null Date object, and one that requires an explicit parameter-- a long integer which represents the amount of time in milliseconds that has passed since some day in 1970.
    I have imported the java utility with this bit of code,
    import java.util.*;For some reason, however, I am unable to construct a proper date object. I have passed it all different kinds of integers, but to no avail. Can anyone help me understand the documentation a little better so I can figure out what parameter it wants?

    I have researched the documentation for this class, and find three constructors.I find six.
    One that is deprecated,Four that are deprecated.
    one that creates a null Date object,No it doesn't. Would it make sense for a constructor to create a null?
    and one that requires an explicit parameter-- a long integer which represents the amount of time in milliseconds that has passed since some day in 1970.Yup, that's right.
    The Date constructor that doesn't take a parameter
    Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
    Not null.
    Instead of java.util.Date, it is usually appropriate to use java.util.Calendar and its concrete subclass java.util.GregorianCalendar.
    The static method Calendar.getInstance()
    Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default locale.
    See the documentation for other methods which allow you to manipulate the Date represented by the instance of Calendar.
    luck, db

Maybe you are looking for

  • Is it possible to share iTunes Library between Mac and PC?

    My wife has a HUGE collection of audio and videos, mainly recordings of workshops she's involved with. Total size is many hundreds of MB, too much for her laptop. If we create a new library on a large external HD (formatted for PC), should she be abl

  • Certificates installtion . Pls advice urgent

    For File --XI --- File Secure scenario with FTPS I am reading this link: https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/964f67ec-0701-0010-bd88-f995abf4e1fc Pls explain me following Points: 1.Do In the visual admin of XI I need t

  • Transfer order issue

    Hi all, There are six line items in delivery. When i am trying to create a transfer order with reference to the delivery, only 4 line items is appearing in TO. I checked and found that there are two TO's against the delivery and both are deleted. But

  • The arrow select tool does not marquee

    The arrow select tool does not work properly.  At times it marquees and some other times it doesn't. Please help.

  • Software upload and reload

    Hi ! Is it possible to upload or reload software throgh my laptop ?If yes , please help how to go about. Solved! Go to Solution.