Testing a class help needed

Hi, I have to do the following :
(1)Write a class called Student with the following private member variables:
name [String]
id [long]
marks [float]
(2)It must have the following methods:
Methods to set name, set ID, and set marks
Eg: public void setName(String newName) { … }
Methods getName, getID, getMarks, eg:
public long getID() {
return id;
(3)Note that the set and get methods do not normally display messages on screen. However, setMarks should display an error if the marks are not in the range 0 - 100, and set the member variable marks to 0.
(4)To test the Student class, write a Test Class that creates a Student object and sets its name, ID and marks. The program should then display the student's name and marks in a message box.
Its parts (3) and (4) Im having trouble with. Im not sure is part 3 correct and cant check it if I dont know what to do for part 4
import javax.swing.JOptionPane;
public class Student {
      * OBP
     private String name;  // Student's name.
     private long ID;  // Unique ID number for this student.
     private float marks;   // Grade
     private static int nextUniqueID = 0;
     // keep track of next available unique ID number
     Student(String newName)
          // Names Student, assigns the student a unique ID number
          name = newName;
          nextUniqueID++;
          ID = nextUniqueID;
     public String getName()
          return name;
     public long getID()
          return ID;
     public float getMarks()
          return marks;
     public void setName(String newName)
          name = newName;
     public void setID(long newID)
          ID = newID;
     public void setMarks(float newMarks)
          if (newMarks >=0 && newMarks <=100)
          marks = newMarks;
          else
               JOptionPane.showMessageDialog(null, "Marks must be >=0 and <=100");
               marks=0;
}Im still new to this so be gentle :P
Thanks

pierrot_2 wrote:
>
No, not quite. It means, if you want to do this...
Student mySt = new Student();... then your Student class has to have this...
public class Student{
public Student(){
}... but it doesn't, so you can't.Just figured that one out.
Huh? You're the one who said what the syntax should be with the private variables and public methods etc. So instead of doing this...
mySt.setID;//wrong syntax... you have to follow the rules you wrote in the Student class definition...
mySt.setID((long)34);//right syntax... but then on this particular method, your Student class has already assigned an ID value (in the constructor), so that undermines your own logic.Its an assignment, hence not technically my logic, just doing what it says and now trying to understand it.
... that's what I'd like to know.If you look at the first post its clearly an assignment I needed help with and it tells you what to do, which I (Yes, "I") did, so now trying to do the Test Class and understand it is the tricky bit.
New Student class (so far):
import javax.swing.JOptionPane;
public class Student {
     private String name;  // Student's name.
     private long ID;  // ID number for this student.
     private float marks;   // Grade
     public Student()
     //Removed Unique ID part...Should this do something??
     public String getName()
          return name;
     public long getID()
          return ID;
     public float getMarks()
          return marks;
     public void setName(String newName)
          name = newName;
     public void setID(long newID)
          ID = newID;
     public void setMarks(float newMarks)
          if (newMarks >=0 && newMarks <=100)
               marks = newMarks;
          else
               JOptionPane.showMessageDialog(null, "Marks must be >=0 and <=100");
               marks=0;
}New Test class:
import javax.swing.JOptionPane;
public class Test{
     public static void main(String[] args)
          String newName = "Dave";
          long newID = 8731543;
          float newMarks = 1010;
          Student mySt = new Student();
          mySt.setName(newName);
          mySt.setID(newID);
          mySt.setMarks(newMarks);
          JOptionPane.showMessageDialog(null, "Name: " + newName + " Marks: " + newMarks );
}The error message that mark is >100 comes up but then so does "Name: Dave Marks:1010.0" even though marks should be set to 0?
Am I still far off? Its 2:45am here and I need to hand this in as soon as possible so am I in for an all nighter?

Similar Messages

  • GUI swing class help needed

    hi, i just need some help to create a bar kind of object (like a bar of battery shown in mobile phones).
    the information i have is in percentage from 0-100%. and what i have planned is that:
    the bar will be split into four:
    from 0-25: one bar will be colored green.
    26-49 "
    50-74 "
    75-100
    the bar information will be from the battery left percentage as mentioned above.
    also if the battery is below 25% the GUI should give an alert (possible red screen with big "alert"..)
    I started doing the frame but got stuck on the bar. pls can you help.
    im looking for nothing complex like make it very accurate to each value of infor. thanks

    Hi,
    You can use a JProgressBar (min 0 max 4)...
    Or make a custom bar with some filled rectangles ...
    Olek
    Edited by: Olek on Oct 11, 2007 10:01 AM

  • Swing class help needed

    hi, i just need some help to create a bar kind of object (like a bar of battery shown in mobile phones).
    the information i have is in percentage from 0-100%. and what i have planned is that:
    the bar will be split into four:
    from 0-25: one bar will be colored green.
    26-49 "
    50-74 "
    75-100 "
    the bar information will be from the battery left percentage as mentioned above.
    also if the battery is below 25% the GUI should give an alert (possible red screen with big "alert"..)
    I started doing the frame but got stuck on the bar. pls can you help.
    im looking for nothing complex like make it very accurate to each value of infor. thanks

    I am sorry if the Gradients were a bit confusing and they weren't exactly what you were asking for but that is what I did for my program.
    What you will do is that your meter will have basically 4 Rectangle objects.
    The logic to determine which Rectangles you will paint to the screen will intuitively go into the paint(Graphics g) method.
    Pseudo-Code:
    public void paint(Graphics g) {
      //set desired color on graphics context
      //switch percentage
      //case percentage = 100
      //fill Rectangle1
      //case percentage <= 75%
      //fill rectangle 2
      //case percentage <= 50%
      //fill rectangle 3
      //case percentage <= 25%
      //fill rectangle 4
      //end switch
    Keep in mind not to put break statements in your switch so that all necessary blocks get colored.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Class help needed.

    i have declared 3 variables in a class, x and y are coordiantres
    public class Robot
    private double x;
    private double y;
    private double Orientation;
    public Robot()
         x = 0;
         y = 0;
         Orientation = 0;
    public (double px, double py, double pOrientation)
         x = px;
         y= py;
         Orientation = pOrientation;
    public double getX()
    return x;
    public double getY()
    return y;
    public double getOrientation()
    return Orientation;
    public void turnRight (double pDeg) //Degrees
    Orientation= Orientation + pDeg;
    public void moveForward (double pDis)
    how do i get the moveforward i have been given the code written below. in the method also been given dx = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to radians
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    stuck on what to do there, thanks

    >
    how do i get the moveforward i have been given the
    code written below. in the method also been given dx
    = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to
    radians
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    A seems to be angle from the x axis that your robot is facing. Therefore replace it with your member variable orientation
    To get your new x, do x = x + dx;
    To get your new y, do y = y + dy;

  • Help needed, M getting this message sandbox environment error no test user account, when downloading any application from iTunes, friend told me to sign out and sign in iTunes it might solve the problem but instead I cannot login I to my itune account.

    Help needed,
    I am getting this message sandbox environment error no test user account, when downloading any application from iTunes, friend told me to sign out and sign in iTunes it might solve the problem , and i triyed it but still  I cannot login I to my itune account. Same message keeping. Popping up,  this problem started supricly today.

    Take a look at the instructions here.
    http://www.technogal.net/2012/03/this-is-not-test-user-account-please.html

  • How do I reorder songs in a playlist in the new itunes??? I can no longer just click and drag. When I click, it doesn't move!!!! Need help ASAP- trying to prepare for an aerobics class and need songs in a specific order!

    How do I reorder songs in a playlist in the new itunes??? I can no longer just click and drag. When I click, it doesn't move!!!! Need help ASAP- trying to prepare for an aerobics class and need songs in a specific order!

    Vera,
    Use View > View Options, and set 'Sort By" to "Manual Order."
    Then you will be able to drag-n-drop songs up and down the list.

  • Help Needed in Creating Java Class and Java Stored Procedures

    Hi,
    Can anyone tell how can i create Java Class, Java Source and Java Resource in Oracle Database.
    I have seen the Documents. But i couldn't able to understand it correctly.
    I will be helpful when i get some Examples for creating a Java Class, Java Source and Stored Procedures with Java with details.
    Is that possible to Create a Java class in the oracle Database itself ?.
    Where are the files located for the existing Java Class ?..
    Help Needed Please.
    Thanks,
    Murali.v

    Hi Murali,
    Heres a thread which discussed uploading java source file instead of runnable code on to the database, which might be helpful :
    Configure deployment to a database to upload the java file instead of class
    The files for the java class you created in JDev project is located in the myworks folder in jdev, eg, <jdev_home>\jdev\mywork\Application1\Project1\src\project1
    Hope this helps,
    Sunil..

  • Trying to make a class to read in strings, help needed

    hello
    i have this class that reads in numbers here is the code
    import java.io.*;
    public class readNumber {
         public static int readlnt()
              throws java.io.IOException
              BufferedReader str= new BufferedReader(new InputStreamReader(System.in));
              String input;
              int res = 0;
              Integer num = new Integer(res);//create integer object
              input = str.readLine();//read input and return a string
              return num.parseInt(input);//convert String to an int and return
              }// end of read method
         }//end of class numberi was trying to makr one to read in words i have this so far
    import java.io.*;
    public class readWord {
         public static int readlnt()
              throws java.io.IOException
              BufferedReader str= new BufferedReader(new InputStreamReader(System.in));
              String input;
              String res = null;
              String word = new String(res);
              input = str.readLine();
              return word.parseword(input);
              }// end of read method
         }//end of class numberi need a little help with the readWord class, any advice you can give would be great
    thanks alot
    Anthony

    Your basic logic is probably going to be something like this:
    (a) read from the stream until you get a letter. (discard spaces at the beginning of a line, or between words)
    (b) create a string or a string buffer that contains the letter you just read.
    (c) read from the stream as long as you're getting letters, appending them to the end of the string or string buffer. When you get a character that isn't a letter, discard it, and return what you've built up.
    This assumes you want to discard punctuation marks, spaces, carriage returns, etc.

  • Help Needed on a similar but not same class loader problem

    Hi,
    Please help...
    There is a ClassLoader called MyLoader that overrides default findClass() method to decrypt already encrypted class files available in a separate jar file.
    MyClass also contains a public static method launchMe() method that starts off with a call similar to loadClass("ApplicationMainClass");
    The MyLoader class is also encrypted
    I modified the default launcher (c) code to:
    First find the encrypted MyLoader file then decrypt it and create a byte array.
    The byte array, along with the system class loader and other required arguments, is passed to DefineClass native method (defined in jvm.dll)
    Note: The system class loader class has been instantiated using static method ClassLoader.getSystemClassLoader() through Java's invocation API.
    The DefineClass succeeds and I'm able to instantiate MyLoader and later call launchMe() to start application.
    Now i come to the problem:
    I'm not able to use any class other that those in rt.jar (i.e.standard classes) in MyLoader class. I end up with a runtime error ClassDefNotFoundError while trying to load any third party jar.
    The classes i need are present in class path and also in the local jre's ext that i use to launch my app.
    Although i can avoid using third party jar in MyLoader but if there is any way...
    Piyush

    make sure that third party jar resides in your library.....
    or else put rt.jar and external jars under same folder
    this is matter of path.... no else than this.......
    cheers
    Rajesh42

  • A Little Help Needed (Date Class)

    I have the following three classes:
    Solution.as
    package
       public class Solution implements IDateCreator
             public function Solution()
    public function releaseToLastDate(d:Date):Date
    IDateCreator.as
    package
       public interface IDateCreator
             function releaseToLastDate(d:Date):Date;
    DateTest.as
    package {
        import flash.display.Sprite
       private var a1:Date  = new Date (2009, 10, 6);
       private var  a2:Date = new Date(2010 , 12);
    private var b1:Date  = new Date (1987, 11, 6);
    private var b2:Date  = new Date (1988, 12);
    private var solution:Solution;
    public function DateTest()
    solution = new Solution();
    var yearTestPassed:Boolean;
    var monthTestPassed:Boolean;
    yearTestPassed = (solution.releaseToLastDate(a1).fullYearUTC = a2.fullYearUTC) && (solution.releaseToLastDate(b1).fullYearUTC == b2.fullYearUTC);
    monthTestPassed = (solution.releaseToLastDate(a1).fullMonthUTC = a2.fullMonthUTC) && (solution.releaseToLastDate(b1).fullMonthUTC == b2.fullMonthUTC);
    trace(“Year Test Passed:” + yearTestPassed);
    trace(“Month Test Passed:” + monthTestPassed);
    I need to figure out what goes in the releeaseToLastDate function in the Solution class order for both boolean expressions to be true. These classes are what i have written so far, and i just need assistance on what needs to go in place of those question marks.

    UseOneAsMany is the function you need to use.
    It takes three parameters:
    1 --- The node you want to duplicated
    2 --- How many times you want to duplicated
    3 --- The context you want to place for it.
    Regards
    Liang

  • Help needed to run JSTL 1.1 in Tomcat 6.0.16

    Hi All,Help needed to run JSTL 1.1 in Tomcat 6.0.16. I am trying to run the example given in http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html The example tries to connect to MySQL database from JSP using JSTL and JNDI Datasource.I am running the example using Eclipse 3.4.2 using Sysdeo plugin to start and stop Tomcat server from Eclipse IDE.
    My web.xml file has <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    </web-app>
    and test.jsp has proper taglib directives
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    I have placed the jstl.jar and standard.jarof the jakarta-taglibs-standard-1.1.2.zip under E:\Deepa\workspace\DBTest\WebContent\WEB-INF\lib directory also placedcontext.xml file under E:\Deepa\workspace\DBTest\WebContent\META-INF and the content of context.xml is as below
    <Context path="/DBTest" docBase="DBTest"
    debug="5" reloadable="true" crossContext="true">
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="deepa" password="mysql" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/>
    </Context>
    Now while running the example, Eclipse creates one DBTest.xml file under C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf\Catalina\localhost
    which has the following line:
    <Context path="/DBTest" reloadable="true" docBase="E:\Deepa\workspace\DBTest" workDir="E:\Deepa\workspace\DBTest\work" />
    I am getting the following error when running http://localhost/DBTest/WebContent/test.jsp
    in Browser:
    <HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/sql cannot be resolved in either web.xml or the jar files deployed with this application
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:51)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:116)
    org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:315)
    org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:148)
    org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:431)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:494)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1444)
    org.apache.jasper.compiler.Parser.parse(Parser.java:138)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:216)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:103)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:154)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:315)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:282)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    In the Tomcat Server console, I am getting the following error:
    INFO: Server startup in 7295 ms
    May 20, 2009 6:36:48 AM org.apache.jasper.compiler.TldLocationsCache processWebDotXml
    WARNING: Internal Error: File /WEB-INF/web.xml not found
    May 20, 2009 6:36:48 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet jsp threw exception
    org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/sql cannot be resolved in either web.xml or the jar files deployed with this application
    what is the problem with my code?
    When running the same example, by creating a local server in Eclipse(creating new Server connection pointing to same Tomcat 6.0 installation) it runs fine without any error.

    Hi evnafets,
    Wow, very helpful information, great insight into working of Eclipse. Thanks a lot.
    I have one more question. I have a context.xml file under {color:#0000ff}E:\Deepa\workspace\DBTest\WebContent\META-INF{color} folder and that has the Resource element to connect to MySQL database:
    {code{color:#000000}}{color}<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true">
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="deepa" password="mysql" driverClassName="com.mysql.jdbc.Driver"
    {color:#0000ff}url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/>{color}
    {color:#0000ff}</Context>{color}As usual when running application in local Tomcat server of Eclipse, this data source works fine. But when I run the application on Tomcat, by starting Sysdeo plugin from Eclipse, the DBTest.xml file created in C:\Tomcat 6.0\conf\Catalina\localhost has the context entry as<Context path="/DBTest" reloadable="true" docBase="E:\Deepa\workspace\DBTest\WebContent" workDir="E:\Deepa\workspace\DBTest\work">
    </Context>The<Resource> element I have specified in the context.xml of \WebContent\META-INF folder is not taken into account by Tomcat and it gives the following error:May 21, 2009 5:20:04 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet jsp threw exception
    javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "org.apache.tomcat.dbcp.dbcp.SQLNestedException_: Cannot create JDBC driver of class '' for connect URL 'null'"
    _at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(_QueryTagSupport.java:276_)
    at org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(_QueryTagSupport.java:159_)
    at org.apache.jsp.test_jsp._jspx_meth_sql_005fquery_005f0(_test_jsp.java:113_)
    at org.apache.jsp.test_jsp._jspService(_test_jsp.java:66_)
    at org.apache.jasper.runtime.HttpJspBase.service(_HttpJspBase.java:70_)
    at javax.servlet.http.HttpServlet.service(_HttpServlet.java:717_)
    at org.apache.jasper.servlet.JspServletWrapper.service(_JspServletWrapper.java:374_)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(_JspServlet.java:342_)
    at org.apache.jasper.servlet.JspServlet.service(_JspServlet.java:267_)
    at javax.servlet.http.HttpServlet.service(_HttpServlet.java:717_)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(_ApplicationFilterChain.java:290_)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(_ApplicationFilterChain.java:206_)
    at org.apache.catalina.core.StandardWrapperValve.invoke(_StandardWrapperValve.java:233_)
    at org.apache.catalina.core.StandardContextValve.invoke(_StandardContextValve.java:191_)
    at org.apache.catalina.core.StandardHostValve.invoke(_StandardHostValve.java:128_)
    at org.apache.catalina.valves.ErrorReportValve.invoke(_ErrorReportValve.java:102_)
    at org.apache.catalina.core.StandardEngineValve.invoke(_StandardEngineValve.java:109_)
    at org.apache.catalina.connector.CoyoteAdapter.service(_CoyoteAdapter.java:286_)
    at org.apache.coyote.http11.Http11Processor.process(_Http11Processor.java:845_)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(_Http11Protocol.java:583_)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(_JIoEndpoint.java:447_)
    at java.lang.Thread.run(_Thread.java:619_)
    {code}
    So to overcome this error I had to place the <Resource> element in DBTest.xml under C:\Tomcat 6.0\conf\Catalina\localhost {color:#000000}and then it works fine. {color}{color:#ff0000}*Why is the context.xml file in META-INF not considered by Tomcat server using Sysdeo Plugin?*
    *Thanks,*
    *Deepa*{color}
    {color}
    Edited by: Deepa76 on May 26, 2009 9:32 PM

  • HELP needed Desperately

    I am very new to programming and I have been trying very hard to get these working. I really need help.
    First I have two buttons; one is a JButton which I intend to click and save data to a file. See Code:
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // I DON'T know how write the code that can use jButton3 to save to
    // the hard drive HELP PLEASE.
    Question two
    I am trying to use another JButton to send an email to my email address from within Java Please see code: below.
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    public void postMail( String recipients[ ], String subject,
    String message , String from) throws MessagingException{
    boolean debug = false;
    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", "[email protected]");
    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    addressTo[i] = new InternetAddress(recipients);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject("subject");
    msg.setContent(message, "text/plain");
    Transport.send(msg);
    public void postMail( String recipients[ ], String subject,
    String message , String from) throws MessagingException{
    boolean debug = false;
    Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", "[email protected]");
    //create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    addressTo[i] = new InternetAddress(recipients[i]);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");
    //Setting the Subject and Content Type
    msg.setSubject("subject");
    msg.setContent(message, "text/plain");
    Transport.send(msg);
    HELP PLEASE

    What does sending e-mail have to do with a JButton? Why do you have all this code in an action method? Can you ever envision where you'd want to send e-mail in a context other than a JButton? If the answer is yes, you should move that e-mail code out into a separate class where you can test it and let any other class that needs it just instantiate an instance and call its methods.
    %

  • Help need regarding Java Reflection

    I need help in programming the following:
    I have to generate a test Harness for OOP.This program that automatically tests
    classes by instantiating them, selecting methods of these instantiated objects randomly or
    using some criteria, invoking them, and using the returned values as input parameters to
    invoke other methods. I have to use Java Reflection for this and methods must be of generic type!
    For this
    I have to generate a tree of functions(say 2 or 3).The functions could be say:int f(int){} and int g(int){}. or Int f(String), String g(float),Float h(int)..I have to create a tree of these function set and traverse them in BFS or DFS and generate combinations of these functions keeping some upper bound for the number of functions genrated(10) and size of combinations of functions(say 5).The output of one function should be the input to other function(so recursive).If any combination failed,then record(or throw exception).This all should be done using java reflection.The input can be provided though annotations or input file.This file can result in recording even the output for each function. I have tried using Junit for testing methods.My code with is following:I have two classes ClassUnderTestTests(which tests the methods of ClassUnderTest) and ClassUnderTest shown below
    //Test Harness class
    public class ClassUnderTestTests {
         Field[] fields;
         Method[] methods;
         Method minVal;
         Method maxVal;
         Method setVal1;
         Method setVal2;
         Method getVal1;
         Method getVal2;
         Class<?> cut;
         ClassUnderTest<Integer> obj1;
         ClassUnderTest<String> obj2;
         @Before public void setUp(){
              try {
                   cut = Class.forName("com.the.ClassUnderTest");
              fields=cut.getDeclaredFields();
              methods=cut.getDeclaredMethods();
              print("Name of the CUT class >>"+ cut.getName());
              print("List of fields >>"+ getFieldNames(fields));
              print("List of Methods >>"+ getMethodNames(methods));
              //creating method objects for the methods declared in the class
              minVal=cut.getDeclaredMethod("minValue");
              minVal.setAccessible(true);
              maxVal=cut.getDeclaredMethod("maxValue");
              maxVal.setAccessible(true);
              setVal1=cut.getDeclaredMethod("setVal1", Comparable.class);
              setVal1.setAccessible(true);
              setVal2 = cut.getDeclaredMethod("setVal2", Comparable.class);
              setVal2.setAccessible(true);
              getVal1=cut.getDeclaredMethod("getVal1");
              getVal1.setAccessible(true);
              getVal2 = cut.getDeclaredMethod("getVal2");
              getVal2.setAccessible(true);
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         @Test public void cutIntegertest(){
              //instantiating the class using the argument constructor for Object 1
              Constructor<?> constr1;
              assertNotNull(cut);
              try {
                   constr1 = cut.getDeclaredConstructor(Comparable.class,Comparable.class);
                   obj1=(ClassUnderTest<Integer>)constr1.newInstance(Integer.valueOf(102),Integer.valueOf(20));
                   assertNotNull(obj1);
                   print("The object of CUT class instantiated with Integer Type");
                   // invoking methods on Object1
              assertEquals(minVal.invoke(obj1),20);
              //Object x = minVal.invoke(obj1);
              print("tested successfully the min of two integers passed");
              assertEquals(maxVal.invoke(obj1),102);
              // maxVal.invoke(obj2);
              //print();
              print("tested successfully the max of two integer values" );
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    @Test public void cutStringTest(){
         assertNotNull(cut);
         Constructor<?> constr2;
              try {
                   constr2 = cut.getDeclaredConstructor(Comparable.class,Comparable.class);
                   obj2=(ClassUnderTest<String>)constr2.newInstance(String.valueOf(obj1.maxValue().toString()),obj2.minValue().toString());
                   //obj2=(ClassUnderTest<String>) cut.newInstance();
                   assertNotNull(obj2);
                   //assertNotNull("obj1 is not null",obj1);
                   //print(obj1.maxValue().toString());
                   print("Object 2 instantiated as String type ");
                   print("setting values on object2 of type string from values of obj1 of type Integer by using toSting()");
                   setVal1.invoke(obj2, obj1.maxValue().toString());
                   setVal2.invoke(obj2, obj1.minValue().toString());//obj2.setVal2(obj1.minValue()
                   assertEquals(getVal1.invoke(obj2),maxVal.invoke(obj1).toString());
                   assertEquals(getVal2.invoke(obj2),minVal.invoke(obj1).toString());
                   print("validating the Assert Equals set from object 1 after conversion to String");
                   print("MinValue for Object2 when Integer treated as String>>> "+minVal.invoke(obj2));
                   print("MaxValue for Object2 when Integer treated as String>>> "+maxVal.invoke(obj2));
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              //obj2.setVal1(obj1.maxValue()
         private static void print(String str){
              System.out.println(str);
         private String getMethodNames(Method[] methods) {
              StringBuffer sb= new StringBuffer();
              for(Method method: methods){
                   sb.append(method.getName()+ " ");
              return sb.toString();
         private String getFieldNames(Field[] fields) {
              StringBuffer sb= new StringBuffer();
              for(Field field: fields){
                   sb.append(field.getName()+ " ");
              return sb.toString();
    //ClassUnderTest
    public class ClassUnderTest <T extends Comparable<T>>{
         //Fields
         private T val1;
         private T val2;
         ClassUnderTest(){}
         public ClassUnderTest(T val1, T val2){
              this.val1=val1;
              this.val2=val2;
         * @return the val1
         public T getVal1() {
              return val1;
         * @param val1 the val1 to set
         public void setVal1(T val1) {
              this.val1 = val1;
         * @return the val2
         public T getVal2() {
              return val2;
         * @param val2 the val2 to set
         public void setVal2(T val2) {
              this.val2 = val2;
         public T maxValue(){
              T max=null;
              if(val1.compareTo(val2) >= 0){
                   max= val1;
              }else {
                   max= val2;
              return max;
         public T minValue(){
              T min=null;
              if(val1.compareTo(val2) < 0){
                   min= val1;
              }else {
                   min= val2;
              return min;
    This code throws Null Pointer Exception if CutStringtest function(I think on calling obj1 in tht function) Please suggest!

    Well, I can't help you specifically since I'm not into reflection too much, but here are some ideas:
    * Either learn how to set breakpoints and single step through your code, or pepper your code with a lot more meaningful System.out.println() statements.
    * Come up with simple test cases, pass them first, then progressively more complex test cases, until you test all possible situations. Try to get each test case to test only a single concept and not multiple concepts at the same time. If your code is broken on more than one concept, you will not be able to isolate each concept by itself to fix it without separating it.
    * Consider refactoring your code so each sub-module accomplishes one task in isolation and verify that module can handle each possible situation that its asked to perform.
    * The exception usually tells you what line in your code threw the exception. Look for a line in the exception printout that has the name of your package or class in it.

  • Help needed with java

    Hello everyone
    I'm a Student and new to java and I have been given a question which I have to go through. I have come across a problem with one of the questions and am stuck, so I was wondering if you guys could help me out.
    here is my code so far:
    A Class that maintains Information about a book
    This might form part of a larger application such
    as a library system, for example.
    @author (your name)
    *@version (a version number or a date)*
    public class Book
    // instance variables or fields
    private String author;
    private String title;
    Set the author and title when the book object is constructed
    public Book(String bookAuthor, String bookTitle)
    author = bookAuthor;
    title = bookTitle;
    Return The name of the author.
    public String getAuthor()
    return author;
    Return The name of the title.
    public String getTitle()
    return title;
    and below are the questions that I need to complete. they just want me to add codes to my current one, but the problem is I don't know where to put them and how I should word them, if that makes sense.
    Add a further instance variable/field pages to the Book class to store the number of pages in the book.
    This should be of type int and should be set to 0 in the Constructor.
    Add a second Constructor with signature
    public Book(String bookAuthor, String bookTitle, int noPages) so it has a third parameter passed to it as well as the author and title;
    this parameter is used - obviously?? - to initialise the number of pages.
    Note: This is easiest done by making a copy of the existing Constructor and adding the parameter.
    Add a getPages() accessor method that returns the number of pages in the book.
    Add a method printDetails() to your Book class. This should print out the Author title and number of pages to the Terminal Window. It is your choice as to how the data is formatted, perhaps all on one line, perhaps on three, and with or without explanatory text. For instance you could print out in the format:
    Title: Robinson Crusoe, Author: Daniel Defoe, Pages:226
    Add a further instance variable/field refNumber() to your Book class. This stores the Library's reference number. It should be of type String and be initialised to the empty String "" in the constructor, as its initial value is not passed in as a parameter. Instead a public mutator method with the signature:
    public void setRefNumber(String ref) should be created. The body of this method should assign the value of the method parameter ref to the refNumber.
    Add a corresponding getRefNumber() accessor method to your class so you can check that the mutator works correctly
    Modify your printDetails() method to include printing the reference number of the book.
    However the method should print the reference number only if it has been set - that is the refNumber has a non-zero length.
    If it has not been set, print "ZZZ" instead.
    Hint Use a conditional statement whose test calls the length() method of the refNumber String and gives a result like:
    Title: Jane Eyre, Author: Charlotte Bronte, Pages:226, RefNo: CB479 or, if the reference number is not set:
    Title: Robinson Crusoe, Author: Daniel Defoe, Pages:347, RefNo: ZZZ
    Modify your setRefNumber() method so that it sets the refNumber field only if the parameter is a string of at least three characters. If it is less than three, then print an error message (which must contain the word error) and leave the field unchanged
    Add a further integer variable/field borrowed to the Book class, to keep a count of the number of times a book has been borrowed. It should (obviously??) be set to 0 in the constructor.
    Add a mutator method borrow() to the class. This should increment (add 1 to) the value of borrowed each time it is called.
    Include an accessor method getBorrowed() that returns the value of borrowed
    Modify Print Details so that it includes the value of the borrowed field along with some explanatory text
    PS. sorry it looks so messey

    1. In the future, please use a more meaningful subject. "Help needed with java" contains no information. The very fact that you're posting here tells us you need help with Java. The point of the subject is to give the forum an idea of what kind of problem you're having, so that individuals can decide if they're interested and qualified to help.
    2. You need to ask a specific question. If you have no idea where to start, then start here: [http://home.earthlink.net/~patricia_shanahan/beginner.html]
    3. When you post code, use code tags. Copy the code from the original source in your editor (NOT from an earlier post here, where it will already have lost all formatting), paste it in here, highlight it, and click the CODE button.

  • JCmboBox setSelectedIndex help needed !!!!!!!!!!!!

    hi,
    I hope it's a trivial question but I am not able to solve it so need your help plz. I have a demo program if you run it you will see what I mean. Actually I am adding items to my JComboBox dynamically. My problem is that if I add the items with the same name and then explicitly set them selected my first item with same name is always highlighted and selected even though I say to select the last item which I add. But when I pull down the comboBox my first item with the same name is selected and highlighted not the last one. Please run the program and see. How can I solve this problem help needed.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ComboBoxDemo extends JPanel {
    JButton picture;
    public ComboBoxDemo() {
    String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
    // Create the combo box, select the pig
    final JComboBox petList = new JComboBox(petStrings);
    picture = new JButton("ADD");
    picture.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    petList.addItem("TEST ");
                   int nodeTotal =     petList.getItemCount();
                   petList.setSelectedIndex(nodeTotal-1);
    setLayout(new BorderLayout());
    add(petList, BorderLayout.NORTH);
    add(picture, BorderLayout.SOUTH);
    setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    public static void main(String s[]) {
    JFrame frame = new JFrame("ComboBoxDemo");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.setContentPane(new ComboBoxDemo());
    frame.pack();
    frame.setVisible(true);
    I want to select the last item I add even if there exists an item with same name.
    Any help is greatly appreciated.
    Thanks.

    never mind I got the answer.
    Tnaks

Maybe you are looking for

  • No table names appear (only Stored Procs) when connected to SQLServer w/dbo

    Greetings, I'm using Crystal Reports 11, connecting to a databse on SQL Server 2005. I am on Windows 7. I also have the problem on Windows Server 2003 Starting from a blank database, I create my connection through ODBC, and when I expand my database,

  • Finding parent node using hierarchical query

    * Is it possible to find the parent record for a given child record in Oracle 8i using hierarchical queries? * For instance, if I have the following table:MyTable col1 col2 col3* The following query returns the tree structure:SELECT *   FROM MyTable

  • Hover background bug in IE?

    I am going spare. At one point my code was looking pretty good. Now it is all completely in a muddle. By trying to put hover backgrounds on my links, the whole positioning is out. Problems: 1. Why do my borders not line up in Safari, on my nav bar. 2

  • Stacking SGE2010P with another SGE2010P

    Hi, I would like to ask on how to stack 2 SGE2010P switches which particular port on the ethernet is to be use for the stacking. Because for SGE2000P we can use 12 and 24 to do stacking. Kindly help me on this issue Best Regards, Gilbert Gimeno

  • Computation on a button push?

    Can you do a computation on a button press? I have a makeshift weekly calendar that I have 2 buttons under...previous and next. I want to push that button and to calculate the monday +7 for the next or the monday -7 for the last. I cant seem to have