Need help with calling method

I'm new to Java, trying to pass a required class so I can graduate this semester, and I need help figuring out what is wrong with the code below. My assignment is to create a program to convert celsius to fahrenheit and vice versa using Scanner for input. The program must contain 3 methods - main, convert F to C, method, and convert C to F method. Requirements of the conversion methods are one parameter which is an int representing temp, return an int representing calculated temp after doing appropriate calculation, should not display info to user, and should not take in info from user.
The main method is required to ask the user to input a 1 for converting F to C, 2 for C to F, and 3 to end the program. It must include a while loop that loops until the user enters a 3, ask the user to enter a temp, call the appropriate method to do the conversion, and display the results. I'm having trouble calling the conversion methods and keep getting the following 2 compiler errors:
cannot find symbol
symbol : method farenheitToCelsius(int)
location: class WondaPavoneTempConverter
int celsius = farenheitToCelsius(intTemp);
^
cannot find symbol
symbol : method celsiusToFarenheit(int)
location: class WondaPavoneTempConverter
int farenheit = celsiusToFarenheit(intTemp);
The code is as follows:
public static void main(String[] args) {
// Create a scanner
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a temperature
System.out.println("Enter the temperature you wish to convert as a whole number: ");
int intTemp = scanner.nextInt();
System.out.println("You entered " + intTemp + " degrees.");
// Prompt the user to enter "1" to convert to Celsius, "2" to convert to
// Farenheit, or "3" to exit the program
System.out.println("Enter 1 to convert to Celsius, 2 to convert to Farenheit, or 3 to exit.");
int intConvert = scanner.nextInt();
// Convert temperature to Celsius or Farenheit
int celsius = farenheitToCelsius(intTemp);
int farenheit = celsiusToFarenheit(intTemp);
while (intConvert >= 0) {
// Convert to Celsius
if (intConvert == 1) {
System.out.println("Celsius is " + celsius + " degrees.");
// Convert to Farenheit
else if (intConvert == 2) {
System.out.println("Farenheit is " + farenheit + " degrees.");
// Exit program
else if (intConvert == 3) {
break;
else {
System.out.println("The number you entered is invalid. Please enter 1, 2, or 3.");
//Method to convert Celsius to Farenheit
public static int celsiusToFahrenheit(int cTemp) {
return (9 / 5) * (cTemp + 32);
//Method to convert Farenheit to Celsius
public static int fahrenheitToCelsius(int fTemp) {
return (5 / 9) * (fTemp - 32);
I readily admit I'm a complete dunce when it comes to programming - digital media is my area of expertise. Can anyone point me in the right direction? This assignment is due very soon. Thanks.

1) consider using a boolean variable in the while statement and converting it to true if the input is good.
while (inputNotValid)
}2) put the code to get the input within the while loop. Try your code right now and enter the number 30 when your menu requests for input and you'll see the infinite loop.... and why you need to request input within the loop.
3) Fix your equations. You are gonig to have to do some double calcs, even if you convert it back to int for the method return. Otherwise the results are just plain wrong. As a good test, put in the numbers -40, 0, 32, 100, and 212. Are the results as expected? (-40 is the only temp that is the same for both cent and fahr). I recommend doing double calcs and then casting the result to int in the return. for example:
int a = (int) (20 + 42.0 / 3);  // the 42.0 forces the compiler to do double calc.4) One of your equations may still be plain wrong even with this fix. Again, run the test numbers and see.
5) Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
  // your code block goes here.
[/code]

Similar Messages

  • Need help with Sound Methods

    Hi, I am new to java and need help with sound methods.
    q: create a new method that will halve the volume of the positive values and double the volume of the negative values.
    Message was edited by:
    Apaula30

    duplicate message #2

  • I need help with this method, i don't know how to call it correct.

    public void method397(byte byte0, int i)
            if(byte0 != 6)
                for(int j = 1; j > 0; j++);
            aByteArray1405[anInt1406++] = (byte)(i + cacheMod.method246());
        }This code is for a Game client im making for a 2dmmorpg, the method was refactored by a friend but he isn't online at the moment because his on holiday; This method sends a packet to the server, i have handled it in the server;
    So i would think you would call it like this;
    super.engineStream.method397((byte)6, 103);But that gives me a huge exception, so please could someone explain how i could fix?
    Thanks
    Ill get the error in a second.

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at Gui.ClientStreamLoader(Gui.java:328)
            at Gui.actionPerformed(Gui.java:323)
            at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
            at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
            at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
            at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
            at javax.swing.AbstractButton.doClick(Unknown Source)
            at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
            at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknow
    Source)
            at java.awt.Component.processMouseEvent(Unknown Source)
            at javax.swing.JComponent.processMouseEvent(Unknown Source)
            at java.awt.Component.processEvent(Unknown Source)
            at java.awt.Container.processEvent(Unknown Source)
            at java.awt.Component.dispatchEventImpl(Unknown Source)
            at java.awt.Container.dispatchEventImpl(Unknown Source)
            at java.awt.Component.dispatchEvent(Unknown Source)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
            at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
            at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
            at java.awt.Container.dispatchEventImpl(Unknown Source)
            at java.awt.Component.dispatchEvent(Unknown Source)
            at java.awt.EventQueue.dispatchEvent(Unknown Source)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.run(Unknown Source)

  • Need help with drawLine method

    Hello,
    I've been having trouble with a recent programming assignment and the prof isn't being very helpful. I need to call the drawLine method to plot a line between (0,0) and two coordinates entered by the user; is there a way to do this without a JPanel? Here are the specs:
    I've already done Part 1., just posting it to give a complete representation of the assignment.
    Part 1. Implement a ComplexNumber class to represent complex numbers (z = a + bi).
    1) Instance variables:
    private int real; /* real part */
    private int imag; /* imaginary part */
    2) Constructor:
    public ComplexNumber ( int realVal, int imagVal )
    { /* initialize real to realVal and imag to imagVal */ }
    3) Get/Set functions:
    public int getReal ( )
    { /* returns the real part */ }
    public int getImag ( )
    { /* returns the imaginary part */ }
    public void setReal ( int realVal )
    { /* sets real to realVal */ }
    public void setImag ( int imagVal )
    { /* sets imag to imagVal */ }
    Part 2. Implement a ComplexNumberPlot class (with a main method) that gets complex
    numbers from the user and plots them. The user will be prompted a complex number until
    he/she enters 0. The numbers will be input from the keyboard (System.in) and displayed
    in the plot as they are entered. Assume that the user will enter the numbers in blank
    separated format. For example, if the user wants to enter three complex numbers: 3 + 4i,
    5 + 12i, and 15 + 17i, the input sequence will be:
    3 4
    5 12
    15 17
    0 0
    To plot a complex number, you need to draw a line between (0,0) and (real, imag) using
    the drawLine method.
    Name your classes as ComplexNumber and ComplexNumberPlot.
    For simplicity, you can assume that the complex numbers input by the user fall
    into the first quadrant of the complex plane, i.e. both real and imaginary values
    are positive.
    Thanks for any help!

    Ok I've made some progress, here is what I've got.
    public class ComplexNumber
    private int real;
    private int imag;
    public ComplexNumber (int realVal, int imagVal)
    real = realVal;
    imag = imagVal;
    public int getReal()
    return real;
    public int getImag()
    return imag;
    public void setReal(int realVal)
    real = realVal;
    public void setImag(int imagVal)
    imag = imagVal;
    import java.util.Scanner;
    import java.awt.*;
    import javax.swing.*;
    public class ComplexNumberPlot
    public static void main (String [] args)
    ComplexNumber num = new ComplexNumber (1,0);
    Scanner scan = new Scanner (System.in);
    System.out.println("Enter a complex number(s):");
    num.setReal(scan.nextInt());
    num.setImag(scan.nextInt());
    while (num.getReal() + num.getImag() != 0)
    num.setReal(scan.nextInt());
    num.setImag(scan.nextInt());
    System.out.println();
    JFrame frame = new JFrame ("ComplexNumberPlot");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    ComplexPanel panel = new ComplexPanel();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    class ComplexPanel extends JPanel
    public ComplexPanel()
    setPreferredSize (new Dimension(150,150));
    public void PaintComponent (Graphics page)
    super.paintComponent(page);
    page.drawLine(0,0,100,100);
    However
    1) The JPanel pops up but no line is drawn.
    2) I am not sure how to get the variables I'm scanning for to work in the drawLine method
    Thanks for all your help so far.

  • Need help with Call By Reference on cRIO-9012

    I have a RT application running on a cRIO-9012 in which I am attempting to establish references to a variable number of clones of the PID Autotuning (Temperature).vi, and then passing these references to a FOR loop in which I am opening each clone with a Call By Reference node to perform the PID.  Essentially, I am trying to make the PID Autotuning (Temperature).vi accept an array of process variables, similar to the behaviour that some of the simpler PID VIs provide out-of-the-box. 
    The code I am using to obtain the references is here:
    ...and the code within the control loop where I am trying to do the processing is here:
    The problem I am encountering, according to the Highlight Execution tool, is that all inputs to the Call By Reference node are present and reach the node, but all processing stops at this point on the first iteration and the cRIO hangs.  I cannot stop the SubVI or the RT parent VI without performing a software restart on the target.
    I don't know if I am using the Call By Reference node or Open VI Reference functions incorrectly, or if there is a problem with the VI being part of a library, or if something else is wrong.  Any help would be appreciated.
    Sean

    I'm not sure this is your issue, but I think there's a conflict between opening a bunch of rereferences, and then setting the asynchronous call pool size for one of them.You don't need asynchronous execution here, you just need reentrant parallel execution (you may not even need the parallel part; your current code, if it worked, would execute sequentially, and the PID calculation is just math so should be quick and may not benefit from parallel execution). You do need reentrant execution to maintain separate data spaces.
    Try opening the references with the 0x08 (Prepare for Reentrant Run) flag instead. Remove the Populate Asynchronous Call Pool. If this works, you can run in parallel by enabling For loop parallelism - but you might find that's actually slower, especially on a cRIO.

  • Need help with Calling objects

    I have created an object named "user" and I currently have 1 Frame in my program. The first frame is called "LogonFrame" and the second is called "UserDataFrame".
    In the main method of the application I declare a "User" object as user and then call LogonFrame to retreive the logon_name and password from the user. The logon_name and password will be placed in the User object to be accessed throughout the application.
    When I compile the application I receive the following error message:
    Error: (85) variable user not found in class GL2.LogonFrame
    *I know that 85 is the line number that the error is located
    *GL2 is the name of the package.
    Has anyone ever encountered this error before, and if so how can I fix this error.
    *Listed below is the code used in the User object if it helps at all.
    Jason Franz
    // Copyright (c) 2003 Jason T. Franz
    package GL2;
    * A Class class.
    * <P>
    * @author Jason T. Franz
    public class User extends Object {
    private static int user_id;
    private static String first_name;
    private static String last_name;
    public static void User(){
    user_id = 0;
    first_name = "";
    last_name = "";
    //sets the user ID
    public static void setUserID(int newID){
    user_id = newID;
    //Returns the User ID
    public static int getUserID(){
    return user_id;
    //Sets the User First Name
    public static void setFirstName(String newFirstName){
    first_name = newFirstName;
    //Gets the Users First Name
    public static String getFirstName(){
    return first_name;
    //Sets the Users Last Name
    public static void setLastName(String newLastName){
    last_name = newLastName;
    public static String getLastName(){
    return last_name;
    //Resets all data in the User Class
    public static void reset(){
    user_id = 0;
    first_name = "";
    last_name = "";

    The code below is a small portion of the program.
    If it helps at all I am useing Oracle JDeveloper version 3.2.3 with JDK1.2.2_JDeveloper
    This section is the User object
    // Copyright (c) 2003 Jason T. Franz
    package GL2;
    * A Class class.
    * <P>
    * @author Jason T. Franz
    public class User extends Object {
      private String first_name;
      private String last_name;
      public User(){
        first_name = "Jason";
        last_name = "Franz";
      //Sets the User First Name
      public void setFirstName(String newFirstName){
        first_name = newFirstName;
      //Gets the Users First Name
      public String getFirstName(){
        return first_name;
      //Sets the Users Last Name
      public void setLastName(String newLastName){
        last_name = newLastName;
      public String getLastName(){
        return last_name;
      //Resets all data in the User Class
      public void reset(){
        first_name = "";
        last_name = "";
        logon_name = "";
        user_password = "";
    }Here is the main method.
    // Copyright (c) 2003 Jason T. Franz
    package GL2;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * GL2.DevilsHead
    * <P>
    * @author Jason T. Franz
    public class DevilsHead {
      public User user = new User();
       * Constructor
      public DevilsHead() {
        AddUserFrame frame = new AddUserFrame();
        //Center the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
          frameSize.height = screenSize.height;
        if (frameSize.width > screenSize.width) {
          frameSize.width = screenSize.width;
        frame.setLocation((screenSize.width - frameSize.width)/2, (screenSize.height - frameSize.height)/2);
        frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
        frame.setVisible(true);
       * main
       * @param args
      public static void main(String[] args) {
        try  {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e) {
          e.printStackTrace();
        new DevilsHead();
    }and here is the Frame which calls the user object to display the Information.
    // Copyright (c) 2003 Jason T. Franz
    package GL2;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * A Swing-based top level window class.
    * <P>
    * @author Jason T. Franz
    public class AddUserFrame extends JFrame {
      BorderLayout borderLayout1 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      Button button1 = new Button();
       * Constructs a new instance.
      public AddUserFrame() {
        super();
        try  {
          jbInit();
        catch (Exception e) {
          e.printStackTrace();
       * Initializes the state of this instance.
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        this.setSize(new Dimension(400, 300));
        button1.setLabel("button1");
        button1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button1_actionPerformed(e);
        this.setTitle("Add a User");
        this.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(button1, null);
      void button1_actionPerformed(ActionEvent e) {
        System.out.println(user.getFirstName());
        System.out.println(user.getLastName());
    }The error I receive is
    Error: (51) variable user not found in class GL2.AddUserFrame

  • Help with calling methods of different classes

    I have two classes. In class A I read a line of input from the console
    myVar= x.readLine();
    then I call a method of the same class (A)
    methodA(); i get NULLPOINTEREXCEPTION here
    in this method I wish to call another method but this time of class B so I create an instance of class B in class A
    private B instanceVar;
    and then proceed to create the method call to class B
    instanceVar.methodB(myVar); i get NULLPOINTEREXCEPTION here
    What am I doing wrong?

    What am I doing wrong?Not posting a short snippet of java code that demonstrates your problem.
    In class A I read a line of input from the console
    myVar= x.readLine();
    How is that related to the NPE's?
    then I call a method of the same class (A)
    methodA(); i get NULLPOINTEREXCEPTION hereSomething is probably wrong in methodA(). Impossible to say anything more with the information given.
    private B instanceVar;
    and then proceed to create the method call to class B
    instanceVar.methodB(myVar); i get NULLPOINTEREXCEPTION hereDid you ever assign instanceVar to an actual object with something like instanceVar = new B(); ?

  • Need help with a method

    I am re-writing this method because it does not return the expected data. I
    am still somewhat new to coding in Forte. Please help if you can. The
    error exception message I receive when I run is.....
    This error is a TOOL CODE ERROR
    Detected In:
    Class: RPTClientNumberList
    Method: DBCursor::Open
    Location: 0
    Forte Error Message is:
    No input values supplied for the SQL statement.
    Additional Information:
    **** End of Error ****
    No matter what changes I make to the SQL I still receive this error.
    //: Parameters: pReportCriteria : ClientNumberListReportCriteria
    //: Returns: Array of ClientNumberListReportData
    //: Purpose: To get the data required for the ClientNumberListReportData.
    //: Logic
    //: History: mm/dd/yy xxx comment
    lClientTransfersArray : Array of ClientNumberListReportData = new();
    lResultArray : Array of ClientNumberListReportData =
    new();
    lReportData : ClientNumberListReportData;
    lReportInfo :
    ClientNumberListReportTransactions;
    lThis : TextData =
    'ReportSQLAgent.SelectClientNumberListReportData()';
    lSQL : TextData = new();
    lSQL.SetValue(
    'SELECT C.ClientName aClientName, \
    CN.ClientNumber aClientNumber, \
    CN.ClientNumberID aClientNumberID, \
    T.TeamNumber aIsTeamID, \
    AM.FirstName aFirstName, \
    AM.MiddleName aMiddleName, \
    AM.LastName aLastName \
    FROM SUPER_DBA.Client C, \
    SUPER_DBA.ClientN CN, \
    SUPER_DBA.Team T, \
    SUPER_DBA.OASUSER AM \
    WHERE CN.ClientID = C.ClientID and \
    CN.ISTeamID = T.TeamID
    and \
    CN.IsActive = \'Y\' AND
    CN.AccountMgrID = AM.UserID ');
    // If the criteria contains an ISTeamID, search by it.
    if pReportCriteria.aISTeamID <> cEmptyDropListValue then
    lSQL.concat( ' and CN.ISTeamID = ');
    lSQL.concat( pReportCriteria.aISTeamID );
    end if;
    begin transaction
    lDynStatement : DBStatementHandle;
    lInputDesc : DBDataset;
    lOutputDesc : DBDataset;
    lOutputData : DBDataset;
    lRowType : Integer;
    lStatementType : Integer;
    // The prepare method parses the SQL statement, verifying the
    // syntax and returns a statement identifier (the handle
    lDynStatement)
    // to use as a reference
    lDynStatement = DefaultDBSession.prepare( lSQL, lInputDesc,
    lStatementType );
    // The opencursor method positions the cursor before the first row
    // in the result set
    lRowType = DefaultDBSession.OpenCursor( lDynStatement, lInputDesc,
    lOutputDesc );
    lNumRows : Integer;
    while true do
    lNumRows = DefaultDBSession.FetchCursor( lDynStatement,
    lOutputData );
    if lNumRows <= 0 then
    exit;
    end if;
    lReportData = new();
    lReportData.aFirstName = TextData(
    lOutputData.GetValue(ColumnName='aFirstName')).value;
    lReportData.aMiddleName = TextData(
    lOutputData.GetValue(ColumnName='aMiddleName')).value;
    lReportData.aLastName = TextData(
    lOutputData.GetValue(ColumnName='aLastName')).value;
    lReportData.aClientName = TextData(
    lOutputData.GetValue(ColumnName='aClientName')).value;
    lReportData.aClientNumber = DoubleNullable(
    lOutputData.GetValue(ColumnName='aClientNumber')).TextValue.value;
    lReportData.aClientNumberID = DoubleNullable(
    lOutputData.GetValue(ColumnName='aClientNumberID')).integervalue;
    lReportData.aIsTeamID = IntegerNullable(
    lOutputData.GetValue(ColumnName='aIsTeamID')).TextValue.value;
    lResultArray.AppendRow( lReportData );
    end while;
    // Close the cursor
    DefaultDBSession.CloseCursor( lDynStatement );
    // Remove the cursor to free resources
    DefaultDBSession.RemoveStatement( lDynStatement );
    end transaction;
    for lEach in lResultArray do
    lHistorySQL : TextData = new();
    lHistorySQL.SetValue(
    'SELECT CNH.isActive aIsActive, \
    T.TeamNumber aTeamID, \
    CNH.ModifyDateTime
    aTransactionDate \
    FROM SUPER_DBA.ClientNH CNH, \
    SUPER_DBA.Team T \
    WHERE CNH.ISTeamID = T.TeamID and \
    CNH.ClientNumberID =
    :lResultArray.aClientNumberID ');
    // If a date range was specified, include it in the SQL
    if NOT pReportCriteria.aStartDate.IsNull then
    lHistorySQL.concat( ' and CNH.ModifyDateTime between
    :pReportCriteria.aStartDate ');
    lHistorySQL.concat( ' and :pReportCriteria.aEndDate ');
    end if;
    begin transaction
    lDynStatement : DBStatementHandle;
    lInputDesc : DBDataset;
    lOutputDesc : DBDataset;
    lOutputData : DBDataset;
    lRowType : Integer;
    lStatementType : Integer;
    // The prepare method parses the SQL statement, verifying
    the
    // syntax and returns a statement identifier (the handle
    lDynStatement)
    // to use as a reference
    lDynStatement = DefaultDBSession.prepare( lHistorySQL,
    lInputDesc, lStatementType );
    // The opencursor method positions the cursor before the
    first row
    // in the result set
    lRowType = DefaultDBSession.OpenCursor( lDynStatement,
    lInputDesc, lOutputDesc );
    lNumRows : Integer;
    while true do
    lNumRows = DefaultDBSession.FetchCursor(
    lDynStatement, lOutputData );
    if lNumRows <= 0 then
    exit;
    end if;
    lReportInfo = new();
    lReportInfo.aIsActive = TextData(
    lOutputData.GetValue(ColumnName='aIsActive')).value;
    lReportInfo.aISTeamID =
    IntegerNullable(
    lOutputData.GetValue(ColumnName='aTeamID')).TextValue.value;
    lReportInfo.aTransactionDate = DateTimeData(
    lOutputData.GetValue(ColumnName='aTransactionDate'));
    lResultArray.AppendRow( lReportData );
    end while;
    // Close the cursor
    DefaultDBSession.CloseCursor( lDynStatement );
    // Remove the cursor to free resources
    putline( '%1: Removing the cursor.', lThis );
    DefaultDBSession.RemoveStatement( lDynStatement );
    end transaction;
    lLastTeamNumber : string = cEmptyText;
    lKeepRecord : boolean = False;
    if lReportInfo.aISTeamID <> lLastTeamNumber then
    lLastTeamNumber = lReportInfo.aISTeamID;
    lReportInfo.aTransactionDescription = 'New Team Assignment';
    lResultArray.appendRow( lReportInfo );
    end if;
    if lReportInfo.aIsActive = 'N' then
    lReportInfo.aTransactionDescription = 'Team Number Deleted';
    lResultArray.appendRow( lReportInfo );
    end if;
    end for;
    // Success! Excellent!! Return the ClientNumberListReportData!
    return lResultArray;
    exception
    when e : GenericException do
    LogException( e, lThis );
    raise e;
    Lisa M. Tucci - Applications Programmer
    Business Applications Support and Development - West Corporation
    tel.: (402) 964-6360 ex: 208-4360 stop: W8-IS e-mail: lmtucciwest.com

    I am re-writing this method because it does not return the expected data. I
    am still somewhat new to coding in Forte. Please help if you can. The
    error exception message I receive when I run is.....
    This error is a TOOL CODE ERROR
    Detected In:
    Class: RPTClientNumberList
    Method: DBCursor::Open
    Location: 0
    Forte Error Message is:
    No input values supplied for the SQL statement.
    Additional Information:
    **** End of Error ****
    No matter what changes I make to the SQL I still receive this error.
    //: Parameters: pReportCriteria : ClientNumberListReportCriteria
    //: Returns: Array of ClientNumberListReportData
    //: Purpose: To get the data required for the ClientNumberListReportData.
    //: Logic
    //: History: mm/dd/yy xxx comment
    lClientTransfersArray : Array of ClientNumberListReportData = new();
    lResultArray : Array of ClientNumberListReportData =
    new();
    lReportData : ClientNumberListReportData;
    lReportInfo :
    ClientNumberListReportTransactions;
    lThis : TextData =
    'ReportSQLAgent.SelectClientNumberListReportData()';
    lSQL : TextData = new();
    lSQL.SetValue(
    'SELECT C.ClientName aClientName, \
    CN.ClientNumber aClientNumber, \
    CN.ClientNumberID aClientNumberID, \
    T.TeamNumber aIsTeamID, \
    AM.FirstName aFirstName, \
    AM.MiddleName aMiddleName, \
    AM.LastName aLastName \
    FROM SUPER_DBA.Client C, \
    SUPER_DBA.ClientN CN, \
    SUPER_DBA.Team T, \
    SUPER_DBA.OASUSER AM \
    WHERE CN.ClientID = C.ClientID and \
    CN.ISTeamID = T.TeamID
    and \
    CN.IsActive = \'Y\' AND
    CN.AccountMgrID = AM.UserID ');
    // If the criteria contains an ISTeamID, search by it.
    if pReportCriteria.aISTeamID <> cEmptyDropListValue then
    lSQL.concat( ' and CN.ISTeamID = ');
    lSQL.concat( pReportCriteria.aISTeamID );
    end if;
    begin transaction
    lDynStatement : DBStatementHandle;
    lInputDesc : DBDataset;
    lOutputDesc : DBDataset;
    lOutputData : DBDataset;
    lRowType : Integer;
    lStatementType : Integer;
    // The prepare method parses the SQL statement, verifying the
    // syntax and returns a statement identifier (the handle
    lDynStatement)
    // to use as a reference
    lDynStatement = DefaultDBSession.prepare( lSQL, lInputDesc,
    lStatementType );
    // The opencursor method positions the cursor before the first row
    // in the result set
    lRowType = DefaultDBSession.OpenCursor( lDynStatement, lInputDesc,
    lOutputDesc );
    lNumRows : Integer;
    while true do
    lNumRows = DefaultDBSession.FetchCursor( lDynStatement,
    lOutputData );
    if lNumRows <= 0 then
    exit;
    end if;
    lReportData = new();
    lReportData.aFirstName = TextData(
    lOutputData.GetValue(ColumnName='aFirstName')).value;
    lReportData.aMiddleName = TextData(
    lOutputData.GetValue(ColumnName='aMiddleName')).value;
    lReportData.aLastName = TextData(
    lOutputData.GetValue(ColumnName='aLastName')).value;
    lReportData.aClientName = TextData(
    lOutputData.GetValue(ColumnName='aClientName')).value;
    lReportData.aClientNumber = DoubleNullable(
    lOutputData.GetValue(ColumnName='aClientNumber')).TextValue.value;
    lReportData.aClientNumberID = DoubleNullable(
    lOutputData.GetValue(ColumnName='aClientNumberID')).integervalue;
    lReportData.aIsTeamID = IntegerNullable(
    lOutputData.GetValue(ColumnName='aIsTeamID')).TextValue.value;
    lResultArray.AppendRow( lReportData );
    end while;
    // Close the cursor
    DefaultDBSession.CloseCursor( lDynStatement );
    // Remove the cursor to free resources
    DefaultDBSession.RemoveStatement( lDynStatement );
    end transaction;
    for lEach in lResultArray do
    lHistorySQL : TextData = new();
    lHistorySQL.SetValue(
    'SELECT CNH.isActive aIsActive, \
    T.TeamNumber aTeamID, \
    CNH.ModifyDateTime
    aTransactionDate \
    FROM SUPER_DBA.ClientNH CNH, \
    SUPER_DBA.Team T \
    WHERE CNH.ISTeamID = T.TeamID and \
    CNH.ClientNumberID =
    :lResultArray.aClientNumberID ');
    // If a date range was specified, include it in the SQL
    if NOT pReportCriteria.aStartDate.IsNull then
    lHistorySQL.concat( ' and CNH.ModifyDateTime between
    :pReportCriteria.aStartDate ');
    lHistorySQL.concat( ' and :pReportCriteria.aEndDate ');
    end if;
    begin transaction
    lDynStatement : DBStatementHandle;
    lInputDesc : DBDataset;
    lOutputDesc : DBDataset;
    lOutputData : DBDataset;
    lRowType : Integer;
    lStatementType : Integer;
    // The prepare method parses the SQL statement, verifying
    the
    // syntax and returns a statement identifier (the handle
    lDynStatement)
    // to use as a reference
    lDynStatement = DefaultDBSession.prepare( lHistorySQL,
    lInputDesc, lStatementType );
    // The opencursor method positions the cursor before the
    first row
    // in the result set
    lRowType = DefaultDBSession.OpenCursor( lDynStatement,
    lInputDesc, lOutputDesc );
    lNumRows : Integer;
    while true do
    lNumRows = DefaultDBSession.FetchCursor(
    lDynStatement, lOutputData );
    if lNumRows <= 0 then
    exit;
    end if;
    lReportInfo = new();
    lReportInfo.aIsActive = TextData(
    lOutputData.GetValue(ColumnName='aIsActive')).value;
    lReportInfo.aISTeamID =
    IntegerNullable(
    lOutputData.GetValue(ColumnName='aTeamID')).TextValue.value;
    lReportInfo.aTransactionDate = DateTimeData(
    lOutputData.GetValue(ColumnName='aTransactionDate'));
    lResultArray.AppendRow( lReportData );
    end while;
    // Close the cursor
    DefaultDBSession.CloseCursor( lDynStatement );
    // Remove the cursor to free resources
    putline( '%1: Removing the cursor.', lThis );
    DefaultDBSession.RemoveStatement( lDynStatement );
    end transaction;
    lLastTeamNumber : string = cEmptyText;
    lKeepRecord : boolean = False;
    if lReportInfo.aISTeamID <> lLastTeamNumber then
    lLastTeamNumber = lReportInfo.aISTeamID;
    lReportInfo.aTransactionDescription = 'New Team Assignment';
    lResultArray.appendRow( lReportInfo );
    end if;
    if lReportInfo.aIsActive = 'N' then
    lReportInfo.aTransactionDescription = 'Team Number Deleted';
    lResultArray.appendRow( lReportInfo );
    end if;
    end for;
    // Success! Excellent!! Return the ClientNumberListReportData!
    return lResultArray;
    exception
    when e : GenericException do
    LogException( e, lThis );
    raise e;
    Lisa M. Tucci - Applications Programmer
    Business Applications Support and Development - West Corporation
    tel.: (402) 964-6360 ex: 208-4360 stop: W8-IS e-mail: lmtucciwest.com

  • Re: help with calling methods

    TL;DR--OK, here are 2 things for you to check
    1 - are you making changes to your object in a scope as a passed by value variable?
    public void myMethod(MyObject o){
      o.my_int = 66;
    }when you return from this method, my_int will be the same as it was before you entered.
    2 - are you making changes to what you think is your object, but is a local copy?
    class MyClass{
      String s = "This is a test";
      MyClass{
       String s = "My inialized String";
    }even through you changed s in your constructor (you can say any method here), you defined a local variable called s and actually modified the local variable leaving your class variable s altered.

    alright guys all yall who posted replies thanks.
    i found out what was wrong. my program was working perfectly. I had flaws in basic math equations that made me get 0 for all those things.

  • Java Newbie needs help with multi method dialog calculator

    Our example for the unit was the example below... we now must create a 5 method program for a calculator... 1 main method and 4 for the standard operations(+ - * /). It is supposed to utilize Swing for graphics/dialog boxes that ask you for the operation you would like to use(if statements based on which operation they enter), and a prompt that asks you separately for the 2 numbers used.... anyone feel like drawing this skeleton out? I am in class right now and none of my neighbors can figure it out either....
    import javax.swing.JOptionPane;
    public class Payroll
         public static void main(String[] args)
         String name;         //the user's name
         String inputString;  //holds input
         int hours;           //hours worked
         double payRate;      //hourly pay wage
         double grossPay;     //total pay
         //getUser
         name = JOptionPane.showInputDialog("What is your name?");
         //getHours
         inputString = JOptionPane.showInputDialog("How many hours did you work?");
         hours = Integer.parseInt(inputString);
         //getRate
         inputString = JOptionPane.showInputDialog("What is your hourly pay rate?");
         payRate = Double.parseDouble(inputString);
         //setGross
         grossPay = payRate * hours;
         //showGross
         JOptionPane.showMessageDialog(null, "Hello " + name + ". Your gross pay is: " + grossPay); 
         //End
         System.exit(0);
    }

    import javax.swing.JOptionPane;
    public class CalcDiag
         public static void main(String[] args)
         String operation;
         String inputString;
         double num1, num2, total=0;
         inputString = JOptionPane.showInputDialog("What is your first number?");
         num1 = Double.parseDouble(inputString);
         inputString = JOptionPane.showInputDialog("What is your second number?");
         num2 = Double.parseDouble(inputString);
         inputString = JOptionPane.showInputDialog("Please indicate which operation you would like to use: A,S,M,D ?");
         operation = inputString;
         if (operation.equals("A"))
              total = getAdd(num1, num2);
         if (operation.equals("S"))
              total = getSub(num1, num2);
         if (operation.equals("M"))
              total = getMult(num1, num2);
         if (operation.equals("D"))
              total = getDiv(num1, num2);
         JOptionPane.showMessageDialog(null,"Total = "+total);
         System.exit(0);
    public static double getAdd(double x, double y)
              return x+y;
    public static double getSub(double x,double y)
              return x-y;
    public static double getMult(double x, double y)
              return x*y;
    public static double getDiv(double x, double y)
              return x/y;
    }your welcome

  • Need help with threads?.. please check my approach!!

    Hello frnds,
    I am trying to write a program.. who monitors my external tool.. please check my way of doing it.. as whenever i write programs having thread.. i end up goosy.. :(
    first let me tell.. what I want from program.. I have to start an external tool.. on separate thread.. (as it takes some time).. then it takes some arguments(3 arguments).. from file.. so i read the file.. and have to run tool.. continously.. until there are arguments left.. in file.. or.. user has stopped it by pressing STOP button..
    I have to put a marker in file too.. so that.. if program started again.. file is read from marker postion.. !!
    Hope I make clear.. what am trying to do!!
    My approach is like..
    1. Have two buttons.. START and STOP on Frame..
    START--> pressed
    2. check marker("$" sign.. placed in beginning of file during start).. on file..
         read File from marker.. got 3 arg.. pass it to tool.. and run it.. (on separate thread).. put marker.. (for next reading)
         Step 2.. continously..
    3. STOP--> pressed
         until last thread.. stops.. keep running the tool.. and when last thread stops.. stop reading any more arguments..
    Question is:
    1. Should i read file again and again.. ?.. or read it once after "$" sign.. store data in array.. and once stopped pressed.. read file again.. and put marker ("$" sign) at last read line..
    2. how should i know when my thread has stopped.. so I start tool again??.. am totally confused.. !!
    please modify my approach.. if u find anything odd..
    Thanks a lot in advance
    gervini

    Hello,
    I have no experience with threads or with having more than run "program" in a single java file. All my java files have the same structure. This master.java looks something like this:
    ---master.java---------------------------------------------------
    import java.sql.*;
    import...
    public class Master {
    public static void main(String args []) throws SQLException, IOException {
    //create connection pool here
    while (true) { // start loop here (each loop takes about five minutes)
    // set values of variables
    // select a slave process to run (from a list of slave programs)
    execute selected slave program
    // check for loop exit value
    } // end while loop
    System.out.println("Program Complete");
    } catch (Exception e) {
    System.out.println("Error: " + e);
    } finally {
    if (rSet1 != null)
    try { rSet1.close(); } catch( SQLException ignore ) { /* ignored */ }
    connection.close();
    -------end master.java--------------------------------------------------------
    This master.java program will run continuously for days or weeks, each time through the loop starting another slave process which runs for five minutes to up to an hour, which means there may be ten to twenty of these slave processes running simultaneously.
    I believe threads is the best way to do this, but I don't know where to locate these slave programs: either inside the master.java program or separate slave.java files? I will need help with either method.
    Your help is greatly appreciated. Thank you.
    Logan

  • Need Help with a getText method

    Gday all,
    I need help with a getText method, i need to extract text from a JTextField. Although this text then needs to converted to a double so that i can multiply a number that i have already specified. As you may of guessed that the text i need to extract already will be in a double format.e.g 0.1 or 0.0000004 etc
    Thanks for your help
    ps heres what i have already done its not very good though
    ToBeConverted.getText();
    ( need help here)
    double amount = (and here)
    total = (amount*.621371192);
    Converted.setText("= " + total);

    Double.parseDouble( textField.getText() );

  • Need Help With File Matching Records

    I need help with my file matching program.
    Here is how it suppose to work: FileMatch class should contain methods to read oldmast.txt and trans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.)
    When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
    Here is my following program code:
    // Exercise 14.8: CreateTextFile.java
    // creates a text file
    import java.io.FileNotFoundException;
    import java.lang.SecurityException;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import org.egan.AccountRecord;
    import org.egan.TransactionRecord;
    public class CreateTextFile
      private Formatter output1;  // object used to output text to file
      private Formatter output2;  // object used to output text to file
      // enable user to open file
      public void openTransFile()
        try
          output1 = new Formatter("trans.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openTransFile
      // enable user to open file
      public void openOldMastFile()
        try
          output2 = new Formatter("oldmast.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openOldMastFile
      // add transaction records to file
      public void addTransactionRecords()
        // object to be written to file
        TransactionRecord record1 = new TransactionRecord();
        Scanner input1 = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
          "To terminate input, type the end-of-file indicator",   
          "when you are prompted to enter input.",
          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
          "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s\n%s",
           "Enter account number (> 0) and amount.","? ");
        while (input1.hasNext())  // loop until end-of-file indicator
          try // output values to file
            // retrieve data to be output
            record1.setAccount(input1.nextInt());    // read account number
            record1.setAmount(input1.nextDouble());  // read amount
            if (record1.getAccount() > 0)
              // write new record
              output1.format("%d %.2f\n", record1.getAccount(), record1.getAmount());
            } // end if
            else
              System.out.println("Account number must be greater than 0.");
            } // end else
          } // end try
          catch (FormatterClosedException formatterClosedException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input1.nextLine(); // discard input so user can try again
          } // end catch
          System.out.printf("%s %s\n%s", "Enter account number (> 0) ",
            "and amount.","? ");
        } // end while
      } // end method addTransactionRecords
      // add account records to file
      public void addAccountRecords()
        // object to be written to file
        AccountRecord record2 = new AccountRecord();
        Scanner input2 = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
          "To terminate input, type the end-of-file indicator",   
          "when you are prompted to enter input.",
          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
          "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s\n%s",
           "Enter account number (> 0), first name, last name and balance.","? ");
        while (input2.hasNext())  // loop until end-of-file indicator
          try // output values to file
            // retrieve data to be output
            record2.setAccount(input2.nextInt());    // read account number
            record2.setFirstName(input2.next());      // read first name
            record2.setLastName(input2.next());       // read last name
            record2.setBalance(input2.nextDouble());  // read balance
            if (record2.getAccount() > 0)
              // write new record
              output2.format("%d %s %s %.2f\n", record2.getAccount(), record2.getFirstName(),
                record2.getLastName(), record2.getBalance());
            } // end if
            else
              System.out.println("Account number must be greater than 0.");
            } // end else
          } // end try
          catch (FormatterClosedException formatterClosedException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input2.nextLine(); // discard input so user can try again
          } // end catch
          System.out.printf("%s %s\n%s", "Enter account number (> 0),",
            "first name, last name and balance.","? ");
        } // end while
      } // end method addAccountRecords
      // close file
      public void closeTransFile()
        if (output1 != null)
          output1.close();
      } // end method closeTransFile
      // close file
      public void closeOldMastFile()
        if (output2 != null)
          output2.close();
      } // end method closeOldMastFile
    } // end class CreateTextFile--------------------------------------------------------------------------------------------------
    // Exercise 14.8: CreateTextFileTest.java
    // Testing class CreateTextFile
    public class CreateTextFileTest
       // main method begins program execution
       public static void main( String args[] )
         CreateTextFile application = new CreateTextFile();
         application.openTransFile();
         application.addTransactionRecords();
         application.closeTransFile();
         application.openOldMastFile();
         application.addAccountRecords();
         application.closeOldMastFile();
       } // end main
    } // end class CreateTextFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.8: TransactionRecord.java
    // A class that represents on record of information
    package org.egan; // packaged for reuse
    public class TransactionRecord
      private int account;
      private double amount;
      // no-argument constructor calls other constructor with default values
      public TransactionRecord()
        this(0,0.0); // call two-argument constructor
      } // end no-argument AccountRecord constructor
      // initialize a record
      public TransactionRecord(int acct, double amt)
        setAccount(acct);
        setAmount(amt);
      } // end two-argument TransactionRecord constructor
      // set account number
      public void setAccount(int acct)
        account = acct;
      } // end method setAccount
      // get account number
      public int getAccount()
        return account;
      } // end method getAccount
      // set amount
      public void setAmount(double amt)
        amount = amt;
      } // end method setAmount
      // get amount
      public double getAmount()
        return amount;
      } // end method getAmount
    } // end class TransactionRecord -------------------------------------------------------------------------------------------------
    // Exercise 14.8: AccountRecord.java
    // A class that represents on record of information
    package org.egan; // packaged for reuse
    import org.egan.TransactionRecord;
    public class AccountRecord
      private int account;
      private String firstName;
      private String lastName;
      private double balance;
      // no-argument constructor calls other constructor with default values
      public AccountRecord()
        this(0,"","",0.0); // call four-argument constructor
      } // end no-argument AccountRecord constructor
      // initialize a record
      public AccountRecord(int acct, String first, String last, double bal)
        setAccount(acct);
        setFirstName(first);
        setLastName(last);
        setBalance(bal);
      } // end four-argument AccountRecord constructor
      // set account number
      public void setAccount(int acct)
        account = acct;
      } // end method setAccount
      // get account number
      public int getAccount()
        return account;
      } // end method getAccount
      // set first name
      public void setFirstName(String first)
        firstName = first;
      } // end method setFirstName
      // get first name
      public String getFirstName()
        return firstName;
      } // end method getFirstName
      // set last name
      public void setLastName(String last)
        lastName = last;
      } // end method setLastName
      // get last name
      public String getLastName()
        return lastName;
      } // end method getLastName
      // set balance
      public void setBalance(double bal)
        balance = bal;
      } // end method setBalance
      // get balance
      public double getBalance()
        return balance;
      } // end method getBalance
      // combine balance and amount
      public void combine(TransactionRecord record)
        balance = (getBalance() + record.getAmount()); 
      } // end method combine
    } // end class AccountRecord -------------------------------------------------------------------------------------------------
    // Exercise 14.8: FileMatch.java
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import org.egan.AccountRecord;
    import org.egan.TransactionRecord;
    public class FileMatch
      private Scanner inTransaction;
      private Scanner inOldMaster;
      private Formatter outNewMaster;
      private Formatter theLog;
      // enable user to open file
      public void openTransFile()
        try
          inTransaction = new Scanner(new File("trans.txt"));
        } // end try
        catch (FileNotFoundException fileNotFoundException)
          System.err.println("Error opening file.");
          System.exit(1);
        } // end catch
      } // end method openTransFile
      // enable user to open file
      public void openOldMastFile()
        try
          inOldMaster = new Scanner(new File("oldmast.txt"));
        } // end try
        catch (FileNotFoundException fileNotFoundException)
          System.err.println("Error opening file.");
          System.exit(1);
        } // end catch
      } // end method openOldMastFile
      // enable user to open file
      public void openNewMastFile()
        try
          outNewMaster = new Formatter("newmast.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openNewMastFile
      // enable user to open file
      public void openLogFile()
        try
          theLog = new Formatter("log.txt");
        catch (SecurityException securityException)
          System.err.println("You do not have write access to this file.");
          System.exit(1);
        } // end catch
        catch (FileNotFoundException filesNotFoundException)
          System.err.println("Error creating file.");
          System.exit(1);
      } // end method openLogFile
      // update records
      public void updateRecords()
        TransactionRecord transaction = new TransactionRecord();
        AccountRecord account = new AccountRecord();
        try // read records from file using Scanner object
          System.out.println("Start file matching.");
          while (inTransaction.hasNext() && inOldMaster.hasNext())
            transaction.setAccount(inTransaction.nextInt());     // read account number
            transaction.setAmount(inTransaction.nextDouble());   // read amount
            account.setAccount(inOldMaster.nextInt());     // read account number
            account.setFirstName(inOldMaster.next());      // read first name 
            account.setLastName(inOldMaster.next());       // read last name
            account.setBalance(inOldMaster.nextDouble());  // read balance
            if (transaction.getAccount() == account.getAccount())
              while (inTransaction.hasNext() && transaction.getAccount() == account.getAccount())
                account.combine(transaction);
                outNewMaster.format("%d %s %s %.2f\n",
                account.getAccount(), account.getFirstName(), account.getLastName(),
                account.getBalance());
                transaction.setAccount(inTransaction.nextInt());     // read account number
                transaction.setAmount(inTransaction.nextDouble());   // read amount
            else if (transaction.getAccount() != account.getAccount())
              outNewMaster.format("%d %s %s %.2f\n",
              account.getAccount(), account.getFirstName(), account.getLastName(),
              account.getBalance());         
              theLog.format("%s%d","Unmatched transaction record for account number ",transaction.getAccount());
          } // end while
          System.out.println("Finish file matching.");
        } // end try
        catch (NoSuchElementException elementException)
          System.err.println("File improperly formed.");
          inTransaction.close();
          inOldMaster.close();
          System.exit(1);
        } // end catch
        catch (IllegalStateException stateException)
          System.err.println("Error reading from file.");
          System.exit(1);
        } // end catch   
      } // end method updateRecords
      // close file and terminate application
      public void closeTransFile()
        if (inTransaction != null)
          inTransaction.close();
      } // end method closeTransFile
      // close file and terminate application
      public void closeOldMastFile()
        if (inOldMaster != null)
          inOldMaster.close();
      } // end method closeOldMastFile
      // close file
      public void closeNewMastFile()
        if (outNewMaster != null)
          outNewMaster.close();
      } // end method closeNewMastFile
      // close file
      public void closeLogFile()
        if (theLog != null)
          theLog.close();
      } // end method closeLogFile
    } // end class FileMatch-------------------------------------------------------------------------------------------------
    // Exercise 14.8: FileMatchTest.java
    // Testing class FileMatch
    public class FileMatchTest
       // main method begins program execution
       public static void main( String args[] )
         FileMatch application = new FileMatch();
         application.openTransFile();
         application.openOldMastFile();
         application.openNewMastFile();
         application.openLogFile();
         application.updateRecords();
         application.closeLogFile();
         application.closeNewMastFile();
         application.closeOldMastFile();
         application.closeTransFile();
       } // end main
    } // end class FileMatchTest-------------------------------------------------------------------------------------------------
    Sample data for master file:
    Master file                         
    Account Number            Name                     Balance
    100                            Alan Jones                   348.17
    300                            Mary Smith                    27.19
    500                            Sam Sharp                   0.00
    700                            Suzy Green                   -14.22Sample data for transaction file:
    Transaction file                    Transaction
    Account Number                  Amount
    100                                         27.14
    300                                         62.11
    300                                         83.89
    400                                         100.56
    700                                         80.78
    700                                         1.53
    900                                         82.17  -------------------------------------------------------------------------------------------------
    My FileMatch class program above has bugs in it.
    The correct results for the newmast.txt:
    100  Alan  Jones  375.31
    300  Mary  Smith  173.19
    500  Sam  Sharp  0.00
    700  Suzy Green  68.09The correct results for the log.txt:
    Unmatched transaction record for account number 400Unmatched transaction record for account number 900------------------------------------------------------------------------------------------------
    My results for the newmast.txt:
    100 Alan Jones 375.31
    300 Mary Smith 111.08
    500 Sam Sharp 0.00
    700 Suzy Green -12.69My results for the log.txt
    Unmatched transaction record for account number 700-------------------------------------------------------------------------------------------------
    I am not sure what is wrong with my code above to make my results different from the correct results.
    Much help is appreciated. Please help.

    From the output, it looks like one problem is just formatting -- apparently you're including a newline in log entries and not using tabs for the newmast output file.
    As to why the numbers are off -- just from glancing over it, it appears that the problem is when you add multiple transaction values. Since account.combine() is so simple, I suspect that you're either adding creating transaction objects incorrectly or not creating them when you should be.
    Create test input data that isolates a single case of this (e.g., just the Mary Smith case), and then running your program in a debugger or adding debugging code to the add/combine method, so you can see what's happening in detail.
    Also I'd recommend reconsidering your design. It's a red flag if a class has a name with "Create" in it. Classes represent bundles of independant state and transformations on that state, not things to do.

  • Need help with my usecase based on transient ViewObject

    I am using 11.1.1.4.0 Jdev version. I need help with my usecase.Been trying it for 2 days but couldn't figure out the issue.
    I have a transientVO . In this VO Rows will be populated programmatically. CountryId is an attribute of this VO. I have created a viewAccessor "CountriesVA" from Country VO of HR schema.
    I have a LOV for the countryId which is based on this VA ,getting countries from CountryTable.
    This is the model part which works fine.
    Before the page load i have called  a method to create a row for this transientVO.Once the row is created i can see the SOC in my page which i have created as below.
    Now i want to insert a row in the transientVO if user selects a country and restrict duplicate entry . (As One row is already created 1st time there will be no rows created.after that rows will be inserted)
    The issue is :: Suppose there are 2 countries. A & B .When user does the following actions :
    Insert A . Done //as 1st entry
    Insert B . Done //as 1st time entry
    Insert A . duplicate not inserted
    Insert B . getting inserted // the bug.
    <af:selectOneChoice value="#{bindings.CountryId.inputValue}"
                            label="#{bindings.CountryId.label}"
                            required="#{bindings.CountryId.hints.mandatory}"
                            shortDesc="#{bindings.CountryId.hints.tooltip}" id="soc1"
                            immediate="true" autoSubmit="true"
                            valueChangeListener="#{pageFlowScope.managedBean.countryIdVC}">
        public void countryIdVC(ValueChangeEvent valueChangeEvent) {
            // Add event code here...
            String oldValue=null;
              setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getOldValue());
              if(evaluateEL("#{bindings.CountryId.attributeValue}")!=null)
             oldValue =evaluateEL("#{bindings.CountryId.attributeValue}").toString();
                    setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getNewValue());
            String newValue=evaluateEL("#{bindings.CountryId.attributeValue}").toString();
            BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
             DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("ViewObj1Iterator");
             //access the underlying RowSetIterator
             RowSetIterator rsi = dciter.getRowSetIterator();
          boolean duplicate=true;
          if(oldValue!=null){
                    rsi.getCurrentRow().setAttribute("CountryId", oldValue);
        //  Row row= rsi.findByKey(new Key(new Object[] { newValue}), 1)[0];
          Key key =new Key(new Object[] { newValue});
          Row row=rsi.getRow(key);
          if(row==null){
          System.err.println(duplicate);
            duplicate=false;
          }else{
            rsi.setCurrentRow(row);
             if(!duplicate){
             //get handle to the last row
             Row lastRow = rsi.last();
             //obtain the index of the last row
             int lastRowIndex = rsi.getRangeIndexOf(lastRow);
             //create a new row
             Row newRow = rsi.createRow();
             newRow.setAttribute("CountryId", newValue);
             //initialize the row
             newRow.setNewRowState(Row.STATUS_INITIALIZED);
             //add row to last index + 1 so it becomes last in the range set
             rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow);
             //make row the current row so it is displayed correctly
             rsi.setCurrentRow(newRow);

    I read the reply from Andrejus Baranovskis and thought of studying and implementing that in my useCase.Well it worked . I implemented the same Logic but rowIteration was done in AppModule.
    Con-Fusion, Bugs, Facts &amp;amp; Workarounds: Iterating through View Object RowIterator Bug.(NOT ADF BUG, Development B…
    http://docs.oracle.com/cd/E15523_01/web.1111/b31974/bcservices.htm#sm0206
    9.7.6 What You May Need to Know About Programmatic Row Set Iteration
    The problem is solved ,the above links helped me solve the problem.
    what i did is i have created a method in appmodule to iterate rows and all the method y operation bindings and my logic works fine ....
    MY Advice to all Adf developers ,though i am not an expert but i can assure you to follow the above process for rowIteration.If you use the  iterator binding in the manage bean to navigate the rows u'll face issues which are unexpected.
    In AppModule :::::
        public boolean createRow(String oldValue,String newValue){
         System.err.println(oldValue+""+newValue);
          ViewObjectImpl vo=getViewObj1();
          boolean duplicate=false;
          if(oldValue!=null){
          RowSetIterator iter = vo.createRowSetIterator(null);
          System.err.println("iterating rows ");
             while (iter.hasNext()) {
                 Row r = iter.next();
                 System.err.println(iter.getRangeIndexOf(r)+" row is "+r.getAttribute("CountryId"));
                 if(r.getAttribute("CountryId").toString().equals(newValue)){
                     duplicate=true;
                     break;
                 // Do something with the current row.
             // close secondary row set iterator
             iter.closeRowSetIterator();
          return duplicate;
    In ManageBean :::::
        public void countryIdVC(ValueChangeEvent valueChangeEvent) {
            // Add event code here...
            String oldValue=null;
           System.err.println("Old Value"+valueChangeEvent.getOldValue());
              setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getOldValue());
              if(evaluateEL("#{bindings.CountryId.attributeValue}")!=null)
             oldValue =evaluateEL("#{bindings.CountryId.attributeValue}").toString();
                    setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getNewValue());
            String newValue=evaluateEL("#{bindings.CountryId.attributeValue}").toString();
            BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
             //access the name of the iterator the table is bound to. Its "allDepartmentsIterator"
             //in this sample
             DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("ViewObj1Iterator");
             //access the underlying RowSetIterator
             RowSetIterator rsi = dciter.getRowSetIterator();
             if(oldValue!=null){
                          rsi.getCurrentRow().setAttribute("CountryId", oldValue);
               OperationBinding operation = bindings.getOperationBinding("createRow");
               operation.getParamsMap().put("oldValue", oldValue);
               operation.getParamsMap().put("newValue", newValue);
          if(!(Boolean)operation.execute()){
          //get handle to the last row
          Row lastRow = rsi.last();
          //obtain the index of the last row
          int lastRowIndex = rsi.getRangeIndexOf(lastRow);
          //create a new row
          Row newRow = rsi.createRow();
          newRow.setAttribute("CountryId", newValue);
          //initialize the row
          newRow.setNewRowState(Row.STATUS_INITIALIZED);
          //add row to last index + 1 so it becomes last in the range set
          System.err.println("Inserting row at index "+lastRowIndex+1);
          rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow);
          //make row the current row so it is displayed correctly
          rsi.setCurrentRow(newRow);
          else{
            System.err.println("Data found So not inserting,only setting current Row");
          Key key =new Key(new Object[] { newValue});
            rsi.setCurrentRow(rsi.getRow(key));

  • Need help with log4j logging tool (org.apache.log4j.*) to log into database

    Hi,
    I need help with log4j logging tool (org.apache.log4j.*) to log into database using JDBCAppender. Have look at my logger code and corresponding log4j.properties file stated below. I'm running this program using Eclipse IDE and it's giving me the following error (highlighted in red) at the end:
    log4j: Parsing for [root] with value=[debug, stdout, Roll, CRSDBAPPENDER].
    log4j: Level token is [debug].
    log4j: Category root set to DEBUG
    log4j: Parsing appender named "stdout".
    log4j: Parsing layout options for "stdout".
    log4j: Setting property [conversionPattern] to [%x %d{HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n].
    log4j: End of parsing for "stdout".
    log4j: Parsed "stdout" options.
    log4j: Parsing appender named "Roll".
    log4j: Parsing layout options for "Roll".
    log4j: Setting property [conversionPattern] to [%x %d{yyyy.MM.dd HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n].
    log4j: End of parsing for "Roll".
    log4j: Setting property [file] to [HelloWorld.log].
    log4j: Setting property [maxBackupIndex] to [10].
    log4j: Setting property [maxFileSize] to [20KB].
    log4j: setFile called: HelloWorld.log, true
    log4j: setFile ended
    log4j: Parsed "Roll" options.
    log4j: Parsing appender named "CRSDBAPPENDER".
    {color:#ff0000}
    Can't find class HelloWorld{color}
    import org.apache.log4j.*;
    public class HelloWorld {
    static Logger log = Logger.getLogger(HelloWorld.class.getName());
    public static void main(String[] args) {
    try{
    // Now, try a few logging methods
    MDC.put("myComputerName", "Ravinder");
    MDC.put("crsServerName", "ARNDEV01");
    log.debug("Start of main()");
    log.info("Just testing a log message with priority set to INFO");
    log.warn("Just testing a log message with priority set to WARN");
    log.error("Just testing a log message with priority set to ERROR");
    log.fatal("Just testing a log message with priority set to FATAL");
    catch(Exception e){
    e.printStackTrace();
    ------------------------- log4j.properties file ------------------------------
    #### Use three appenders - log to console, file and database
    log4j.rootCategory=debug, stdout, Roll, CRSDBAPPENDER
    log4j.debug=true
    # Print only messages of priority WARN or higher for your category
    # log4j.category.your.category.name=WARN
    # Specifically inherit the priority level
    # log4j.category.your.category.name=INHERITED
    #### stdout - First appender writes to console
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%x %d{HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n
    #### Roll - Second appender writes to a file
    log4j.appender.Roll=org.apache.log4j.RollingFileAppender
    ##log4j.appender.Roll.File=${InstanceName}.log
    log4j.appender.Roll.File=HelloWorld.log
    log4j.appender.Roll.MaxFileSize=20KB
    log4j.appender.Roll.MaxBackupIndex=10
    log4j.appender.Roll.layout=org.apache.log4j.PatternLayout
    log4j.appender.Roll.layout.ConversionPattern=%x %d{yyyy.MM.dd HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n
    #### CRSDBAPPENDER - third appender writes to the database
    log4j.appender.CRSDBAPPENDER=org.apache.log4j.jdbc.JDBCAppender
    log4j.appender.CRSDBAPPENDER.Driver=net.sourceforge.jtds.jdbc.Driver
    log4j.appender.CRSDBAPPENDER.URL=jdbc:jtds:sqlserver:/arncorp15:1433;DatabaseName=LOG
    log4j.appender.CRSDBAPPENDER.USER=sa
    log4j.appender.CRSDBAPPENDER.PASSWORD=p8ss3doff
    log4j.appender.CRSDBAPPENDER.layout=org.apache.log4j.PatternLayout
    log4j.appender.CRSDBAPPENDER.sql=INSERT INTO LOG (computername, crsservername, logtime, loglevel, threadname, filename, linenumber, logtext) VALUES ('%X{myComputerName}', '%X{crsServerName}', '%d{dd MMM yyyy HH:mm:ss,SSS}', '%p', '%t', '%F', '%L', '%m')
    #log4j.appender.CRSDBAPPENDER.sql=INSERT INTO LOG(COMPUTERNAME,CRSSERVERNAME,LOGTIME,LOGLEVEL,THREADNAME,FILENAME,LINENUMBER,LOGTEXT) select host_name(),'${CRSServerName}${InstanceName}','%d','%5p','%t','%F','%L','%m%n'
    #log4j.appender.CRSDBAPPENDER.sql=INSERT INTO LOG (computername, crsservername, logtime, loglevel, threadname, filename, linenumber, logtext) VALUES ("%X{myComputerName}", "%X{crsServerName}", "%d{dd MMM yyyy HH:mm:ss,SSS}", "%p", "%t", "%F", "%L", "%m")
    ------------------------------- end of log4j.properties file ------------------------------
    Here is the directory structure of my program. My log4j.properties file and HelloWorld.class file are residing in folder HelloWorld\bin.
    HelloWorld\bin
    HelloWorld\lib
    HelloWorld\src
    Please note - The same program works fine for console and file appender when I comment the database appender part in my properties file.
    Thanks
    Ravinder

    try this :
    log4j.appender.PROJECT.Append=false

Maybe you are looking for

  • Issue with Group Chart of Accounts

    HI All, Good Morning. I have 2 Comp Codes, using different Chart of Accounts and have 0001 as Group Chart of Accounts. When I try to create GL Account in One Comp Code, giving Group Account Number,  I am getting the below error. "Corporate Group Acco

  • How to enable iCloud Keychain for 3rd party apps?

    I came across iCloud Keychain, which if enabled, lets you backup keychain passwords and restore on other iOS devices. Also read that 3rd party apps can integerate iCloud Keychain to their apps in order to ensure that the app's keychain items are back

  • Unable to edit PDF output file

    After report server generating the PDF file, The PDF file cannot be edited by acrobat writer. Is there any method to make the PDF file editable ? Thanks

  • Automatic creation of billing

    Hi, after delivery we have to make an invoice thru t code VF01. in that we give  the delivery number. however , there is an automatic way out of creating an invoice , the moment the delivery is saved . basically the output type at the header level of

  • Disable Pass-through

    Hi I imported a big update.xml with pass-through authentication configuration ... Now I can't log in web admin console as configurator. How can I disable the great pass-through? Big Thanks JXXE