Help tracing code

can anyone help me out with tracing this code. I have the answers at the bottom its just that im not really understanding how to do it, if anyone could help that would be great. thanks.
public class ParamTest {
static void f(int[] a, int[] b, int[][] c) {
int x;
x = a[0];
a[0] = a[1];
a[1] = x;
c[0] = c[1];
c[1] = b;
b[0] = 7;
b = new int[2];
b[0] = 8;
b[1] = 9;
c[0][0] = a[0];
public static void main(String[] args) {
int[] x1 = {0,1};
int[][] x2 = {{2,3},{4,5}};
f(x1, x2[0], x2);
               System.out.println(� x1[0]: � + x1[0] +
                                                                                     � x1[1]: � + x1[1] );
               System.out.println(� x2[0][0]: � + x2[0][0] +
                                                                                     � x2[0][1]: � + x2[0][1] +
     � x2[1][0]: � + x2[1][0] +
                                                                                     � x2[1][1]: � + x2[1][1] );
// answers
x1[0]:_1___ x1[1]:_0___
x2[0][0]:_1___ x2[0][1]:_5___ x2[1][0]: _7___ x2[1][1]: _3___

Do you not understand the code itself or why it's failing?
If the first, I can't really help you.. it's crucial that you understand what the code is supposed to be doing.
If the second, my advice would be to use the following:
System.out.println(someStringHere)after every line of code to verify that the values of each variable are what you expect them to be.

Similar Messages

  • Maestro need help also code is 75957252

    maestro need help also code is 75957252 for bios password reset
    This question was solved.
    View Solution.

    Try
    60635894
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • Maestro need help also code is 75957252 for bios password reset

    maestro need help also code is 75957252 for bios password reset
    This question was solved.
    View Solution.

    Check your other post. I replied there.
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • Differnces between Search Help & Match Codes

    Hi,
    what is the Differences between Search Help & Match Codes ? which is goof to use ?

    Matchcodes were replaced with Search Helps starting with Release 4.0. Please use search helps to assign an input help to a field.
    Existing matchcodes were automatically converted to search helps. A matchcode object is hereby converted to a collective search help with the same name. Each matchcode ID of the matchcode object is converted into an elementary search help with the same name and assigned to the collective search help created from the matchcode object.
    A matchcode is a means of finding data records stored in the system. The matchcode is defined in the ABAP Dictionary in two steps:
    You first define the relevant tables and fields for the search in a matchcode object. A matchcode object describes the set of all possible search paths for a search string.
    You then create one or more matchcode IDs for a matchcode object. A matchcode ID describes a special search path for a search string. The matchcode ID defines the fields or field combinations to be used in the search.
    Search Help
    Use
    With this function you can search for objects, thereby defining and linking different selection conditions for the search help.
    Prerequisites
    You can call this function by:
    · Selecting Object ® Search... () in the main menu bar of the Integration Builder
    · Placing the cursor on a software component version and selecting Search... () in the context menu (only in the Integration Repository)
    In this case the software component version is defined as the search criteria.
    Features
    Defining the Object Type
    You can select the object type in a dropdown list in field Object Type.
    In the design (Integration Repository) you can
    · Select an object type (for example Message Interface)
    · Select a cross-object category (for example Interface Objects)
    In the configuration (Integration Directory) you can select types Values Mapping Group and schema in addition to the individual object types.
    CHECK THIS LINK TO CREATE A SEARCH HELP.
    http://www.sapdevelopment.co.uk/dictionary/shelp/shelp_basic.htm
    CHECK THIS LINK TO CREATE A MATCHCODE OBJECT
    http://searchsap.techtarget.com/tip/1,289483,sid21_gci553386,00.html
    more details...

  • Search helps & match codes - Urgent plz

    Hi ,
    1.   Could any one give me the difference between search helps & match codes.
    2. assume that you are giving input matnr from selection screen.and executed based on input matnr you have generated an interactive report with fields matnr,etc...
    if i want to change that particular matnr realted fields how can i do that from this report.Shell i call mm02 tcode.How to do that.how to pass the selected parameter to the transaction.(screen matnr field.please give me an example.
    Regards
    SAISRI

    Hi,
    Check this example for interactive reporting..which will take you MM02
    TYPE-POOLS: slis.
    DATA: gt_fieldcat TYPE slis_t_fieldcat_alv.
    DATA: BEGIN OF wa_material,
    MATNR LIKE MARA-MATNR,
    END OF wa_material.
    DATA: v_repid TYPE syrepid.
    v_repid = sy-repid.
    DATA it_material LIKE STANDARD TABLE OF wa_material WITH HEADER LINE.
    SELECT * UP TO 100 ROWS
    FROM MARA
    INTO CORRESPONDING FIELDS OF TABLE it_material.
    CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
         EXPORTING
              i_program_name     = v_repid
              i_internal_tabname = 'WA_MATERIAL'
              i_inclname         = v_repid
         CHANGING
              ct_fieldcat        = gt_fieldcat.
    * have hotspot for a PO.
    DATA: s_fieldcat LIKE LINE OF gt_fieldcat.
    s_fieldcat-hotspot = 'X'.
    MODIFY gt_fieldcat FROM s_fieldcat TRANSPORTING hotspot
           WHERE fieldname = 'MATNR'.
    * Pass the program.
    v_repid = sy-repid.
    CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
         EXPORTING
              i_callback_program      = v_repid
              it_fieldcat             = gt_fieldcat
              i_callback_user_command = 'USER_COMMAND'
         TABLES
              t_outtab                = it_material.
    *       FORM display_detail                                           *
    *  -->  UCOMM                                                         *
    *  -->  SELFIELD                                                      *
    FORM user_command USING ucomm LIKE sy-ucomm
    selfield TYPE slis_selfield.
      IF ucomm = '&IC1' AND selfield-fieldname = 'MATNR'.
        READ TABLE it_material INDEX selfield-tabindex.
        IF sy-subrc = 0.
          SET PARAMETER ID 'MAT' FIELD it_material-matnr.
          CALL TRANSACTION 'MM02' AND SKIP FIRST SCREEN.
        ENDIF.
      ENDIF.
    ENDFORM.
    Thanks
    Naren

  • Combo box and Check box..help with code please?

    Here is my problem...i have a list of check boxes and according to which one is checked, i need combo boxes to populate different choices.
    as an easy example im only using 2 check boxes and two combo boxes.
    the check boxes are named Choice 1or2 with export values of 1 and 2
    the Combo Boxes are named List A and List B..
    both containing options that say you checked box 1 and you checked box 2
    any help would be greatly appreciated

    Implode wrote:
    "Help with code please."
    In the future, please use a meaningful subject. Given that you're posting here, it's kind of a given that you're looking for help with the code. The whole point of the subject is to give people a high level idea of what KIND of help with what KIND of code you need, so they can decide if they're interested and qualified to help.
    Exception in thread "main" java.lang.NumberFormatException: For input string: "fgg"
         at java.lang.NumberFormatException.forInputString(Unknown Source)
         at java.lang.Integer.parseInt(Unknown Source)
         at java.lang.Integer.parseInt(Unknown Source)
         at assignment1.Game.Start(Game.java:120)
         at assignment1.RunGame.main(RunGame.java:18)This error message is telling you exactly what's wrong. At line 120 of Game.java, in the Start method (which should start with lowercase "s" to follow conventions, by the way), you're calling Integer.parseInt, but "fgg" is not a valid int.

  • My iphone wont turn on or restore,HELP error code 1015

    My iphone wont turn on or restore,HELP error code 1015

    jailbroken? if so we can't help here, try google.

  • Checking Account and help with code ?

    Hi all..my computer hung up on me, so I'm not sure if my last post went through. First of all thank you all for helping me out the other day with my question on the Bank Account. It continues :)
    I'm trying to work on each class one by one..when I test my Checking Account, it isn't printing out the correct balance. The string method to print this is coming from the Withdrawal class...so I know it has to be somewhere in there but I can't seem to figure out why it isn't totalling the balance...or how to get it too.
    Then when I test my MyBank class, it hangs up on line 63..which I could swear I have written correctly. Again I am getting a NullPointerException and I honestly think I have the line of code written right, but I'm guessing I dont.
    Any help would be appreciated.
    public abstract class BankAccount {
        public static final String bankName = "BrianBank";
        protected String custName;
        protected String pin;
        protected Transaction[] history;
        private double balance;
        private double amt, amount;
        private double bal, initBal;
        private int transactions;
        private final int MAX_HISTORY = 100;
        private int acct;
        protected BankAccount(String cname, String cpin, double initBal) {
         custName = cname;
         pin = cpin;
         balance = initBal;
         history = new Transaction[MAX_HISTORY];
         transactions =0;
        public double getBalance() {
         return balance;
        public void withdraw(double amt) {
         history [transactions] = new Withdrawal (bal, amt);
       balance = bal;
         amount = amt;
         balance -= amt;
       transactions = transactions + 1;     
        public void deposit(double amt) {     
         history [transactions] = new Deposit (bal, amt);
         balance = bal;
         amount = amt;
         balance += amt;
         transactions = transactions +1;
        // abstract method to return account number
        public abstract int getAcctNum();
        // abstract method to return a summary of transactions as a string
        public abstract String getStatement();
    public class CheckingAccount extends BankAccount implements IncursFee
          private int transactions;
          private double balance, initBal, amt;
          private static final int NOFEE_WITHDRAWALS = 10;
          private static final double TRANSACTION_FEE = 5.00;
          public static final String bankName = "iBank";
          public static final int STARTING_ACCOUNT_NUMBER = 10000;
          private int checkingAccountNumber = STARTING_ACCOUNT_NUMBER;
          private static int accountNumberCounter = STARTING_ACCOUNT_NUMBER;
          private String custName;
          private String pin;
          public CheckingAccount (String cname, String cpin, double initBal)
             super (cname, cpin, initBal);
              custName = cname;
              pin = cpin;
             balance = initBal;
             accountNumberCounter++; 
             checkingAccountNumber = accountNumberCounter;
          //initialize a count of transactions
             transactions = 0;          
           public double getBalance()
             return balance;
           public void withdraw(double amt)
            super.withdraw (amt);
             transactions ++;
           public void deposit(double amt)
           super.deposit (amt);
             transactions ++;
           public int getAcctNum ()
             return checkingAccountNumber;     
           public String getStatement ()
             int i = 0;
             String output = "";
             while ( i < history.length && history[i] != null )
                output += history.toString () + "\n";
    i++;
    return output;     
    public void deductFee(double fee)
    if (transactions > NOFEE_WITHDRAWALS)
    {  fee = TRANSACTION_FEE *(transactions - NOFEE_WITHDRAWALS);
    super.withdraw(fee);
    balance -=fee;
    transactions = 0;
    public interface IncursFee {
    public abstract void deductFee(double fee);
    public abstract class Transaction {
    protected double initBal;
    protected double tranAmt;
    // constructor
    protected Transaction(double bal, double amt) {
         initBal = bal;
         tranAmt = amt;
    abstract public String toString();
    public class Withdrawal extends Transaction
         private double initBal;
         private double amount;
         private static NumberFormat fmt = NumberFormat.getCurrencyInstance();
         public Withdrawal (double bal, double amt)
              super (bal, amt);
              initBal = bal;
              amount = amt;
         public String toString ()
         return "Balance : " + fmt.format(initBal) + "\n" + "Withdrawal : " + fmt.format(amount);
    import java.text.NumberFormat;
    public class Deposit extends Transaction
         private double initbal, balance;
         private double amount;
         private static NumberFormat fmt = NumberFormat.getCurrencyInstance();
         public Deposit (double bal, double amt)
         super (bal, amt);
         initbal = bal;
         amount = amt;
         public String toString ()
         return "Balance : " + fmt.format(initbal) + "\n" + "Deposit : " + fmt.format(amount);
    public class TestCheckingAcct {
    public static void main(String[] args) {
         BankAccount b1 = new CheckingAccount("Harry", "1234", 500.0);
         System.out.println (b1.getBalance ());
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.deposit(50);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.deposit(10);
         b1.withdraw(1);
         System.out.println(b1.getStatement());
    // This interface specifies the functionality requirements of a bank
    public interface Bank {
    public abstract int openNewAccount(String customerName, String customerPIN, String accType, double initDepAmount);
    public abstract void processWithdrawal(int accNum, String pin, double amount);
    // executes a deposit on the specified acct by the amount
    public abstract void processDeposit(int accNum, String pin, double amount);
    // returns the balance of acct
    public abstract double processBalanceInquiry(int accNum, String pin);
    // returns summary of transactions
    public abstract String processStatementInquiry(int accNum, String pin);
    import java.util.ArrayList;
    public class MyBank implements Bank
    private ArrayList<BankAccount> savAccounts = new ArrayList<BankAccount>(); //dynamically grows
    private ArrayList<BankAccount> chkAccounts = new ArrayList<BankAccount>(); //dynamically grows
    private SavingsAccount sav;
    private CheckingAccount chk;
    private int accNum;
    private String customerName, customerPIN, accType, pin;
    private double initDepAmount, amount, balance;
    public int openNewAccount(String customerName, String customerPIN, String accType, double initDepAmount)
    this.customerName = customerName;
    this.customerPIN = customerPIN;
    this.accType = accType;
    this.initDepAmount = initDepAmount;
    if ( accType.equals("Savings"))
    BankAccount savAcct = new SavingsAccount(customerName, customerPIN, initDepAmount);
    try
    savAccounts.add(savAcct);
    catch (ArrayIndexOutOfBoundsException savAccounts)
    return savAcct.getAcctNum();
    else
    CheckingAccount chkAcct = new CheckingAccount(customerName, customerPIN, initDepAmount);
         try
    chkAccounts.add(chkAcct);
    catch (ArrayIndexOutOfBoundsException chkAccounts)
    return chkAcct.getAcctNum();
    public void processWithdrawal (int accNum, String pin, double amount)
         this.accNum = accNum;
         this.pin = pin;
         this.amount = amount;
    if (accNum >10000 && accNum < 20000)
         chk.withdraw (amount);
    if (accNum >50000 && accNum <60000)
         sav.withdraw (amount);
    public void processDeposit (int accNum, String pin, double amount)
         this.accNum = accNum;
         this.pin = pin;
         this.amount = amount;
    if (accNum >10000 && accNum < 20000)
         chk.deposit (amount);
    if (accNum >50000 && accNum <60000)
         sav.deposit (amount);
    public double processBalanceInquiry (int accNum, String pin)
         this.accNum = accNum;
         this.pin = pin;
         this.balance = 0;
    if (accNum >10000 && accNum <20000)
         balance = chk.getBalance ();
    if (accNum >50000 && accNum <60000)
         balance = sav.getBalance ();
    return balance;
    public String processStatementInquiry(int accNum, String pin)
         this.accNum = accNum;
         this.pin = pin;
         this.statement = "";
    if (accNum >10000 && accNum <20000)
    statement = chk.getStatement ();
    if (accNum >50000 && accNum <60000)
    statement= sav.getStatement ();
         return statement;

    Here's some quick code review:
    public abstract class BankAccount {
    public static final String bankName =
    me = "BrianBank";
    protected String custName;
    protected String pin;
    protected Transaction[] history;
    private double balance;
    private double amt, amount;
    private double bal, initBal;
    private int transactions;// make MAX_HISTORY private static final, too.
    private final int MAX_HISTORY = 100;
    private int acct;
    protected BankAccount(String cname, String cpin,
    pin, double initBal) {
         custName = cname;
         pin = cpin;
         balance = initBal;
         history = new Transaction[MAX_HISTORY];
         transactions =0;
    public double getBalance() {
         return balance;
    public void withdraw(double amt) {
         history [transactions] = new Withdrawal (bal, amt);
    balance = bal;
         amount = amt;
         balance -= amt;// ++transactions above would be elegant.
    transactions = transactions + 1;     
    public void deposit(double amt) {     
         history [transactions] = new Deposit (bal, amt);
         balance = bal;
         amount = amt;
         balance += amt;
         transactions = transactions +1;
    // abstract method to return account number// why abstract?
    public abstract int getAcctNum();
    // abstract method to return a summary of
    y of transactions as a string// why abstract?
    public abstract String getStatement();
    public class CheckingAccount extends BankAccount
    implements IncursFee
    private int transactions;
    private double balance, initBal, amt;
    private static final int NOFEE_WITHDRAWALS =
    WALS = 10;
    private static final double TRANSACTION_FEE =
    _FEE = 5.00;
    public static final String bankName = "iBank";
    public static final int STARTING_ACCOUNT_NUMBER
    NUMBER = 10000;
    private int checkingAccountNumber =
    mber = STARTING_ACCOUNT_NUMBER;
    private static int accountNumberCounter =
    nter = STARTING_ACCOUNT_NUMBER;// BankAccount has a custName attribute; why does CheckingAccount need
    // one if it extends BankAccount?
    private String custName;
    private String pin;
    public CheckingAccount (String cname, String
    String cpin, double initBal)
    super (cname, cpin, initBal);
    custName = cname;
    pin = cpin;
    balance = initBal;
    accountNumberCounter++;
    checkingAccountNumber =
    tNumber = accountNumberCounter;
    //initialize a count of transactions
    transactions = 0;          
    // same as BankAccount - why rewrite it?
    public double getBalance()
    return balance;
    // same as BankAccount - why rewrite it?
    public void withdraw(double amt)
    super.withdraw (amt);
    transactions ++;
    // same as BankAccount - why rewrite it?
    public void deposit(double amt)
    super.deposit (amt);
    transactions ++;
              // same as BankAccount - why rewrite it?
    public int getAcctNum ()
    return checkingAccountNumber;     
    public String getStatement ()
    int i = 0;
    String output = "";
    while ( i < history.length && history[i] !=
    ory[i] != null )
    output += history.toString () + "\n";
    i++;
    return output;     
    public void deductFee(double fee)
    if (transactions > NOFEE_WITHDRAWALS)
    {  fee = TRANSACTION_FEE *(transactions -
    ansactions - NOFEE_WITHDRAWALS);
    super.withdraw(fee);
    balance -=fee;
    transactions = 0;
    public interface IncursFee {
    public abstract void deductFee(double fee);
    public abstract class Transaction {
    protected double initBal;
    protected double tranAmt;
    // constructor
    // why protected? make it public.
    protected Transaction(double bal, double amt) {
         initBal = bal;
         tranAmt = amt;
    abstract public String toString();
    public class Withdrawal extends Transaction
         private double initBal;
         private double amount;
    private static NumberFormat fmt =
    = NumberFormat.getCurrencyInstance();
         public Withdrawal (double bal, double amt)
              super (bal, amt);
              initBal = bal;
              amount = amt;
         public String toString ()
    return "Balance : " + fmt.format(initBal) + "\n" +
    + "Withdrawal : " + fmt.format(amount);
    import java.text.NumberFormat;
    public class Deposit extends Transaction
         private double initbal, balance;
         private double amount;
    private static NumberFormat fmt =
    = NumberFormat.getCurrencyInstance();
         public Deposit (double bal, double amt)
         super (bal, amt);
         initbal = bal;
         amount = amt;
         public String toString ()
    return "Balance : " + fmt.format(initbal) + "\n" +
    + "Deposit : " + fmt.format(amount);
    public class TestCheckingAcct {
    public static void main(String[] args) {
    BankAccount b1 = new CheckingAccount("Harry",
    , "1234", 500.0);
         System.out.println (b1.getBalance ());
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.deposit(50);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.withdraw(1);
         b1.deposit(10);
         b1.withdraw(1);
         System.out.println(b1.getStatement());
    // This interface specifies the functionality
    requirements of a bank
    public interface Bank {
    public abstract int openNewAccount(String
    String customerName, String customerPIN, String
    accType, double initDepAmount);
    public abstract void processWithdrawal(int
    (int accNum, String pin, double amount);
    // executes a deposit on the specified acct by
    t by the amount
    public abstract void processDeposit(int accNum,
    Num, String pin, double amount);
    // returns the balance of acct
    public abstract double processBalanceInquiry(int
    (int accNum, String pin);
    // returns summary of transactions
    public abstract String
    ring processStatementInquiry(int accNum, String
    pin);
    import java.util.ArrayList;
    public class MyBank implements Bank
    private ArrayList<BankAccount> savAccounts =
    unts = new ArrayList<BankAccount>(); //dynamically
    grows
    private ArrayList<BankAccount> chkAccounts =
    unts = new ArrayList<BankAccount>(); //dynamically
    grows
    private SavingsAccount sav;
    private CheckingAccount chk;
    private int accNum;
    private String customerName, customerPIN,
    erPIN, accType, pin;
    private double initDepAmount, amount, balance;
    public int openNewAccount(String customerName,
    erName, String customerPIN, String accType, double
    initDepAmount)
    this.customerName = customerName;
    this.customerPIN = customerPIN;
    this.accType = accType;
    this.initDepAmount = initDepAmount;
    if ( accType.equals("Savings"))
    BankAccount savAcct = new
    vAcct = new SavingsAccount(customerName, customerPIN,
    initDepAmount);
    try
    savAccounts.add(savAcct);
    catch (ArrayIndexOutOfBoundsException
    Exception savAccounts)
    return savAcct.getAcctNum();
    else
    CheckingAccount chkAcct = new
    hkAcct = new CheckingAccount(customerName,
    customerPIN, initDepAmount);
         try
    chkAccounts.add(chkAcct);
    catch (ArrayIndexOutOfBoundsException
    Exception chkAccounts)
    return chkAcct.getAcctNum();
    public void processWithdrawal (int accNum,
    accNum, String pin, double amount)
         this.accNum = accNum;
         this.pin = pin;
         this.amount = amount;
    if (accNum >10000 && accNum < 20000)
         chk.withdraw (amount);
    if (accNum >50000 && accNum <60000)
         sav.withdraw (amount);
    public void processDeposit (int accNum, String
    String pin, double amount)
         this.accNum = accNum;
         this.pin = pin;
         this.amount = amount;
    if (accNum >10000 && accNum < 20000)
         chk.deposit (amount);
    if (accNum >50000 && accNum <60000)
         sav.deposit (amount);
    public double processBalanceInquiry (int accNum,
    String pin)
         this.accNum = accNum;
         this.pin = pin;
         this.balance = 0;
    if (accNum >10000 && accNum <20000)
         balance = chk.getBalance ();
    if (accNum >50000 && accNum <60000)
         balance = sav.getBalance ();
    return balance;
    public String processStatementInquiry(int accNum,
    m, String pin)
         this.accNum = accNum;
         this.pin = pin;
         this.statement = "";
    if (accNum >10000 && accNum <20000)
    statement = chk.getStatement ();
    if (accNum >50000 && accNum <60000)
    statement= sav.getStatement ();
         return statement;
    Very bad style with those brace placements. Pick a style and stick with it. Consistency is the key.
    Your code isn't very readable.
    You don't have a SavingsAccount here anywhere, even though your MyBank uses one.
    You use JDK 1.5 generics yet you've got ArrayList as the static type on those declarations. Better to use the interface type List as the compile time type on the LHS.
    You have a lot of compile time problems, and some incomprehensible stuff, but I was able to change it enough to my TestCheckingAcct run to completion. No NPE exceptions.
    I'm not sure I agree with your design.
    No SavingsAccount. The accounts I have ALL incur fees - no need for a special interface there. Savings accounts are usually interest bearing. That's the way they behave differently from checking accounts. Where do you have that?
    You rewrite too much code. If you put behavior in the abstract BankingAccount class (a good idea), the whole idea is that concrete classes that extend BankingAccount don't need to overload any methods whose default behavior is correct for them.
    I don't know that I'd have separate Deposit and Withdrawal to implement Transaction. I'd make Transaction concrete and have starting balance, ending balance, and a transaction type String (e.g., "DEPOSIT", "WITHDRAWAL")
    It'd be good to see some thought put into exception handling. I don't see an OverdrawnException anywhere. Seems appropriate.
    No transfer methods from one account to another. I often do that with my bank.
    That's enough to get started.

  • Help with code to print HTML in Java 5

    Hi,
    The following code works and runs successfully..
    However, the printing in Java 1.4.2_03 is better than Java 5 (latest version).
    i.e in particular the characters are not monospaced compared with compiling with Java 1.4.2_03. e.g si so ss squashed together.
    This issue does not seem to occur when running the same code in Java 1.4.2_03. (I haven't tried other 1.4.2 java versions).
    Any help would be appreciated. We really need this working under Java 5 or bust.
    Here is the complete listing ... PrintHtml.java (it uses the DocumentRenderer)
    and following this is the input file.
    import javax.swing.text.html.HTMLDocument;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.IOException;
    import java.io.DataInputStream;
    import java.io.InputStream;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.lang.reflect.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.swing.JEditorPane;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.View;
    import javax.swing.text.html.HTMLDocument;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.text.ParseException;
    public class PrintHtml {
         * Utility helper to convert HTML Text to HTML Document.
         * @param baseUrl URL to be used in order
         * to resolve relative HTML references, in lieu of an
         * HTML BASE tag. May be null, if not required or HTML
         * BASE tag is to be used.
         * @see jbox.view.jfx.JboxHtmlEditor
         * @see jbox.utility.JboxPrint
         * @see jbox.utility.JboxPrintUtil
      public static HTMLDocument htmlTextToHtmlDoc(String htmlText, URL baseUrl)
              try
              //  JboxHtmlEditorKit editorKit = new JboxHtmlEditorKit();
                HTMLEditorKit editorKit = new HTMLEditorKit();
                HTMLDocument doc = (HTMLDocument)editorKit.createDefaultDocument();
                   if (baseUrl != null)
                        try
                             doc.setBase(baseUrl);
                        catch(Exception e)
                             //JboxTraceManager.trace(e);
                   StringReader reader = new StringReader(htmlText);
                   editorKit.read(reader, doc, 0);
             return doc;
              catch(Exception e)
                   //JboxTraceManager.trace(e);
                   return null;
       public static void main(String[] args) {
          System.out.println("printing...");
          HTMLDocument x = new HTMLDocument();
          DocumentRenderer invoice = new DocumentRenderer();
          //invoice.setScaleWidthToFit(false);
          String s = "";
          try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mark.html"));
            InputStreamReader in = new InputStreamReader(bis , "ASCII");
            StringWriter sw = new StringWriter();
            while (true) {
               int datum = in.read();
               if (datum == -1) break;
               sw.write(datum);
            in.close();
            s = sw.toString();
            System.out.println("s="+s);
          catch (IOException e) {
             System.err.println(e);
          HTMLDocument htmldoc = htmlTextToHtmlDoc(s, null);
          invoice.print(htmldoc);
    // the good old infamous DocumentRenderer.
    /*  Copyright 2002
        Kei G. Gauthier
        Suite 301
        77 Winsor Street
        Ludlow, MA  01056
    class DocumentRenderer implements Printable {
    /*  DocumentRenderer prints objects of type Document. Text attributes, including
        fonts, color, and small icons, will be rendered to a printed page.
        DocumentRenderer computes line breaks, paginates, and performs other
        formatting.
        An HTMLDocument is printed by sending it as an argument to the
        print(HTMLDocument) method. A PlainDocument is printed the same way. Other
        types of documents must be sent in a JEditorPane as an argument to the
        print(JEditorPane) method. Printing Documents in this way will automatically
        display a print dialog.
        As objects which implement the Printable Interface, instances of the
        DocumentRenderer class can also be used as the argument in the setPrintable
        method of the PrinterJob class. Instead of using the print() methods
        detailed above, a programmer may gain access to the formatting capabilities
        of this class without using its print dialog by creating an instance of
        DocumentRenderer and setting the document to be printed with the
        setDocument() or setJEditorPane(). The Document may then be printed by
        setting the instance of DocumentRenderer in any PrinterJob.
      protected int currentPage = -1;               //Used to keep track of when
                                                    //the page to print changes.
      protected JEditorPane jeditorPane;            //Container to hold the
                                                    //Document. This object will
                                                    //be used to lay out the
                                                    //Document for printing.
      protected double pageEndY = 0;                //Location of the current page
                                                    //end.
      protected double pageStartY = 0;              //Location of the current page
                                                    //start.
      protected boolean scaleWidthToFit = true;     //boolean to allow control over
                                                    //whether pages too wide to fit
                                                    //on a page will be scaled.
    /*    The DocumentRenderer class uses pFormat and pJob in its methods. Note
          that pFormat is not the variable name used by the print method of the
          DocumentRenderer. Although it would always be expected to reference the
          pFormat object, the print method gets its PageFormat as an argument.
      protected PageFormat pFormat;
      protected PrinterJob pJob;
    /*  The constructor initializes the pFormat and PJob variables.
      public DocumentRenderer() {
        pFormat = new PageFormat();
        pJob = PrinterJob.getPrinterJob();
    /*  Method to get the current Document
      public Document getDocument() {
        if (jeditorPane != null) return jeditorPane.getDocument();
        else return null;
    /*  Method to get the current choice the width scaling option.
      public boolean getScaleWidthToFit() {
        return scaleWidthToFit;
    /*  pageDialog() displays a page setup dialog.
      public void pageDialog() {
        pFormat = pJob.pageDialog(pFormat);
    /*  The print method implements the Printable interface. Although Printables
        may be called to render a page more than once, each page is painted in
        order. We may, therefore, keep track of changes in the page being rendered
        by setting the currentPage variable to equal the pageIndex, and then
        comparing these variables on subsequent calls to this method. When the two
        variables match, it means that the page is being rendered for the second or
        third time. When the currentPage differs from the pageIndex, a new page is
        being requested.
        The highlights of the process used print a page are as follows:
        I.    The Graphics object is cast to a Graphics2D object to allow for
              scaling.
        II.   The JEditorPane is laid out using the width of a printable page.
              This will handle line breaks. If the JEditorPane cannot be sized at
              the width of the graphics clip, scaling will be allowed.
        III.  The root view of the JEditorPane is obtained. By examining this root
              view and all of its children, printView will be able to determine
              the location of each printable element of the document.
        IV.   If the scaleWidthToFit option is chosen, a scaling ratio is
              determined, and the graphics2D object is scaled.
        V.    The Graphics2D object is clipped to the size of the printable page.
        VI.   currentPage is checked to see if this is a new page to render. If so,
              pageStartY and pageEndY are reset.
        VII.  To match the coordinates of the printable clip of graphics2D and the
              allocation rectangle which will be used to lay out the views,
              graphics2D is translated to begin at the printable X and Y
              coordinates of the graphics clip.
        VIII. An allocation Rectangle is created to represent the layout of the
              Views.
              The Printable Interface always prints the area indexed by reference
              to the Graphics object. For instance, with a standard 8.5 x 11 inch
              page with 1 inch margins the rectangle X = 72, Y = 72, Width = 468,
              and Height = 648, the area 72, 72, 468, 648 will be painted regardless
              of which page is actually being printed.
              To align the allocation Rectangle with the graphics2D object two
              things are done. The first step is to translate the X and Y
              coordinates of the graphics2D object to begin at the X and Y
              coordinates of the printable clip, see step VII. Next, when printing
              other than the first page, the allocation rectangle must start laying
              out in coordinates represented by negative numbers. After page one,
              the beginning of the allocation is started at minus the page end of
              the prior page. This moves the part which has already been rendered to
              before the printable clip of the graphics2D object.
        X.    The printView method is called to paint the page. Its return value
              will indicate if a page has been rendered.
        Although public, print should not ordinarily be called by programs other
        than PrinterJob.
      public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
        double scale = 1.0;
        Graphics2D graphics2D;
        View rootView;
    //  I
        graphics2D = (Graphics2D) graphics;
        disableDoubleBuffering(jeditorPane);
    //  II
        jeditorPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE);
        jeditorPane.validate();
    //  III
        rootView = jeditorPane.getUI().getRootView(jeditorPane);
    //  IV
        if ((scaleWidthToFit) && (jeditorPane.getMinimumSize().getWidth() >
        pageFormat.getImageableWidth())) {
          scale = pageFormat.getImageableWidth()/
          jeditorPane.getMinimumSize().getWidth();
          graphics2D.scale(scale,scale);
    //  V
        graphics2D.setClip((int) (pageFormat.getImageableX()/scale),
        (int) (pageFormat.getImageableY()/scale),
        (int) (pageFormat.getImageableWidth()/scale),
        (int) (pageFormat.getImageableHeight()/scale));
    //  VI
        if (pageIndex > currentPage) {
          currentPage = pageIndex;
          pageStartY += pageEndY;
          pageEndY = graphics2D.getClipBounds().getHeight();
    //  VII
        graphics2D.translate(graphics2D.getClipBounds().getX(),
        graphics2D.getClipBounds().getY());
    //  VIII
        Rectangle allocation = new Rectangle(0,
        (int) -pageStartY,
        (int) (jeditorPane.getMinimumSize().getWidth()),
        (int) (jeditorPane.getPreferredSize().getHeight()));
    //  X
        if (printView(graphics2D,allocation,rootView)) {
          return Printable.PAGE_EXISTS;
        else {
          pageStartY = 0;
          pageEndY = 0;
          currentPage = -1;
          return Printable.NO_SUCH_PAGE;
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    /*  print(HTMLDocument) is called to set an HTMLDocument for printing.
      public void print(HTMLDocument htmlDocument) {
        setDocument(htmlDocument);
        printDialog();
    /*  print(JEditorPane) prints a Document contained within a JEDitorPane.
      public void print(JEditorPane jedPane) {
        setDocument(jedPane);
        printDialog();
    /*  print(PlainDocument) is called to set a PlainDocument for printing.
      public void print(PlainDocument plainDocument) {
        setDocument(plainDocument);
        printDialog();
    /*  A protected method, printDialog(), displays the print dialog and initiates
        printing in response to user input.
      protected void printDialog() {
        if (pJob.printDialog()) {
          pJob.setPrintable(this,pFormat);
          try {
            pJob.print();
          catch (PrinterException printerException) {
            pageStartY = 0;
            pageEndY = 0;
            currentPage = -1;
            System.out.println("Error Printing Document");
    /*  printView is a recursive method which iterates through the tree structure
        of the view sent to it. If the view sent to printView is a branch view,
        that is one with children, the method calls itself on each of these
        children. If the view is a leaf view, that is a view without children which
        represents an actual piece of text to be painted, printView attempts to
        render the view to the Graphics2D object.
        I.    When any view starts after the beginning of the current printable
              page, this means that there are pages to print and the method sets
              pageExists to true.
        II.   When a leaf view is taller than the printable area of a page, it
              cannot, of course, be broken down to fit a single page. Such a View
              will be printed whenever it intersects with the Graphics2D clip.
        III.  If a leaf view intersects the printable area of the graphics clip and
              fits vertically within the printable area, it will be rendered.
        IV.   If a leaf view does not exceed the printable area of a page but does
              not fit vertically within the Graphics2D clip of the current page, the
              method records that this page should end at the start of the view.
              This information is stored in pageEndY.
      protected boolean printView(Graphics2D graphics2D, Shape allocation,
      View view) {
        boolean pageExists = false;
        Rectangle clipRectangle = graphics2D.getClipBounds();
        Shape childAllocation;
        View childView;
        if (view.getViewCount() > 0 &&
              !view.getElement().getName().equalsIgnoreCase("td")) {
          for (int i = 0; i < view.getViewCount(); i++) {
            childAllocation = view.getChildAllocation(i,allocation);
            if (childAllocation != null) {
              childView = view.getView(i);
              if (printView(graphics2D,childAllocation,childView)) {
                pageExists = true;
        } else {
    //  I
          if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) {
            pageExists = true;
    //  II
            if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) &&
            (allocation.intersects(clipRectangle))) {
              view.paint(graphics2D,allocation);
            } else {
    //  III
              if (allocation.getBounds().getY() >= clipRectangle.getY()) {
                if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) {
                  view.paint(graphics2D,allocation);
                } else {
    //  IV
                  if (allocation.getBounds().getY() < pageEndY) {
                    pageEndY = allocation.getBounds().getY();
        return pageExists;
    /*  Method to set the content type the JEditorPane.
      protected void setContentType(String type) {
        jeditorPane.setContentType(type);
    /*  Method to set an HTMLDocument as the Document to print.
      public void setDocument(HTMLDocument htmlDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/html",htmlDocument);
    /*  Method to set the Document to print as the one contained in a JEditorPane.
        This method is useful when Java does not provide direct access to a
        particular Document type, such as a Rich Text Format document. With this
        method such a document can be sent to the DocumentRenderer class enclosed
        in a JEditorPane.
      public void setDocument(JEditorPane jedPane) {
        jeditorPane = new JEditorPane();
        setDocument(jedPane.getContentType(),jedPane.getDocument());
    /*  Method to set a PlainDocument as the Document to print.
      public void setDocument(PlainDocument plainDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/plain",plainDocument);
    /*  Method to set the content type and document of the JEditorPane.
      protected void setDocument(String type, Document document) {
        setContentType(type);
        jeditorPane.setDocument(document);
    /*  Method to set the current choice of the width scaling option.
      public void setScaleWidthToFit(boolean scaleWidth) {
        scaleWidthToFit = scaleWidth;
    }The sample input file is "mark.html":::
    <html>
    <head>
    <style type="text/css">
    <!--
    ol { list-style-type: decimal; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    u { text-decoration: underline }
    s { text-decoration: line-through }
    p { font-weight: normal; font-size: medium; margin-top: 15 }
    dd p { margin-top: 0; margin-left: 40; margin-bottom: 0 }
    ol li p { margin-top: 0; margin-bottom: 0 }
    address { color: blue; font-style: italic }
    i { font-style: italic }
    h6 { font-weight: bold; font-size: xx-small; margin-top: 10; margin-bottom: 10 }
    h5 { font-weight: bold; font-size: x-small; margin-top: 10; margin-bottom: 10 }
    h4 { font-weight: bold; font-size: small; margin-top: 10; margin-bottom: 10 }
    h3 { font-weight: bold; font-size: medium; margin-top: 10; margin-bottom: 10 }
    dir li p { margin-top: 0; margin-bottom: 0 }
    h2 { font-weight: bold; font-size: large; margin-top: 10; margin-bottom: 10 }
    b { font-weight: bold }
    h1 { font-weight: bold; font-size: x-large; margin-top: 10; margin-bottom: 10 }
    a { color: blue; text-decoration: underline }
    ul li ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    menu { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    menu li p { margin-top: 0; margin-bottom: 0 }
    table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    sup { vertical-align: sup }
    body { margin-right: 0; font-size: 14pt; font-family: SansSerif; color: black; margin-left: 0 }
    ul li ul li ul { list-style-type: square; margin-left: 25 }
    blockquote { margin-right: 35; margin-top: 5; margin-left: 35; margin-bottom: 5 }
    samp { font-size: small; font-family: Monospaced }
    cite { font-style: italic }
    sub { vertical-align: sub }
    em { font-style: italic }
    table table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    ul li p { margin-top: 0; margin-bottom: 0 }
    ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    var { font-weight: bold; font-style: italic }
    table { border-color: Gray; margin-right: 7; border-style: outset; margin-top: 7; margin-left: 7; margin-bottom: 17 }
    dfn { font-style: italic }
    menu li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    strong { font-weight: bold }
    ul { list-style-type: disc; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    center { text-align: center }
    ul li ul { list-style-type: circle; margin-left: 25 }
    kbd { font-size: small; font-family: Monospaced }
    dir li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    th p { font-weight: bold; padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    ul li menu { list-style-type: circle; margin-left: 25 }
    dt { margin-top: 0; margin-bottom: 0 }
    ol li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    li p { margin-top: 0; margin-bottom: 0 }
    strike { text-decoration: line-through }
    dl { margin-top: 10; margin-left: 10; margin-bottom: 10 }
    tt { font-family: Monospaced }
    ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    dir { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    pre p { margin-top: 0 }
    th { border-color: Gray; border-style: solid; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    pre { font-family: Monospaced; margin-top: 5; margin-bottom: 5 }
    td { border-color: Gray; border-style: inset; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    td p { padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    code { font-size: small; font-family: Monospaced }
    small { font-size: x-small }
    big { font-size: x-large }
    -->
    </style>
    </head>
    <body>
    <p style="margin-top: 0">
    </p>
    <table width="500" cellspacing="20" border="1">
    <tr>
    <td height="330" valign="top">
    <table border="0">
    <tr>
    <td>
    <font size="2">This is to certify that [[Client Name]], born
    on [[Client Date of Birth]], of [[Client Residential
                    Address]], was the holder of motor vehicle driver
    licence number [[Client Licence Number]], first issued on
    [[First Issue Date of Holding]] and expired on [[Holding
                    Expiry Date]].<br></font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    <table width="500" border="2">
    <tr>
    <td>
    <table width="480" border="0">
    <tr>
    <td align="right">
    <font size="2"><br>
    <b>Fred Flintstone<br>Manager</b><br>Records Services Division<br>State
    Police<br>An authorised person for the purposes of the
    Road Act 1986</font>
    </td>
    </tr>
    <tr>
    <td align="left">
    <font size="2"><b>User ID: wzvqv7<br>Dated: 29 November 2006</b>
    </font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    </body>
    </html>

    I have finally cracked it!!!!!!!!!!!!!!!!
    The issue is definitely with Java Sun. "Uneven character spacing when printing JTextComponent"
    It is raised on the http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488219
    And currently in OPEN state, and raised on 31 Oct 2006 and mentions it was caused by fix 4352983.
    So where do we go from here. It's not good because I have tried all later version of the JVM and the issue is still there.
    Why? Because it hasn't been fixed yet. Read the bug report above, as it gives more insight -- and mentions the workaround is NOT good for existing code.
    So the way forward is to use an earlier version of the JVM 5.
    I download the JVM version 1.5.0 (starting version) and works Ok... I would probably think version prior to 4352983 would be Ok too.
    Please vote for this.... We have a workaround (use older version of the JVM).
    So I am very happy.

  • Newbie needing help with code numbers and if-else

    I'm 100% new to any kind of programming and in my 4th week of an Intro to Java class. It's also an on-line class so my helpful resources are quite limited. I have spent close to 10 hours on my class project working out P-code and the java code itself, but I'm having some difficulty because the project seems to be much more advanced that the examples in the book that appear to only be partly directly related to this assignment. I have finally come to a point where I am unable to fix the mistakes that still show up. I'm not trying to get anyone to do my assignment for me, I'm only trying to get some help on what I'm missing. I want to learn, not cheat.
    Okay, I have an assignment that, in a nutshell, is a cash register. JOptionPane prompts the user to enter a product code that represents a product with a specific price. Another box asks for the quanity then displays the cost, tax and then the total amount plus tax, formatted in dollars and cents. It then repeats until a sentinel of "999" is entered, and then another box displays the total items sold for the day, amount of merchandise sold, tax charged, and the total amount acquired for the day. If a non-valid code is entered, I should prompt the user to try again.
    I have this down to 6 errors, with one of the errors being the same error 5 times. Here are the errors:
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:50: 'else' without 'if'
    else //if invalid code entered, output message
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:39: unexpected type
    required: variable
    found : value
    100 = 2.98;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:41: unexpected type
    required: variable
    found : value
    200 = 4.50;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:43: unexpected type
    required: variable
    found : value
    300 = 6.79;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:45: unexpected type
    required: variable
    found : value
    400 = 5.29;
    ^
    C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:47: unexpected type
    required: variable
    found : value
    500 = 7.20;
    ^
    And finally, here is my code. Please be gentle with the criticism. I've really put a lot into it and would appreciate any help. Thanks in advance.
    import java.text.NumberFormat; // class for numeric formating from page 178
    import javax.swing.JOptionPane; // class for JOptionOPane
    public class Sales {
    //main method begins execution ofJava Application
    public static void main( String args[] )
    double quantity; // total of items purchased
    double tax; // total of tax
    double value; // total cost of all items before tax
    double total; // total of items including tax
    double totValue; // daily value counter
    double totTax; // daily tax counter
    double totTotal; // daily total amount collected (+tax) counter
    double item; //
    String input; // user-entered value
    String output; // output string
    String itemString; // item code entered by user
    String quantityString; // quantity entered by user
    // initialization phase
    quantity = 0; // initialize counter for items purchased
    // get first code from user
    itemString = JOptionPane.showInputDialog(
    "Enter item code:" );
    // convert itemString to double
    item = Double.parseDouble ( itemString );
    // loop until sentinel value read from user
    while ( item != 999 ) {
    // converting code to amount using if statements
    if ( item == 100 )
    100 = 2.98;
    if ( item == 200 )
    200 = 4.50;
    if ( item == 300 )
    300 = 6.79;
    if ( item == 400 )
    400 = 5.29;
    if ( item == 500 )
    500 = 7.20;
    else //if invalid code entered, output message
    JOptionPane.showMessageDialog( null, "Invalid code entered, please try again!",
    "Item Code", JOptionPane.INFORMATION_MESSAGE );
    } // end if
    } // end while
    // get quantity of item user
    itemString = JOptionPane.showInputDialog(
    "Enter quantity:" );
    // convert quantityString to int
    quantity = Double.parseDouble ( quantityString );
    // add quantity to quantity
    quantity = quantity + quantity;
    // calculation time! value
    value = quantity * item;
    // calc tax
    tax = value * .07;
    // calc total
    total = tax + value;
    //add totals to counter
    totValue = totValue + value;
    totTax = totTax + tax;
    totTotal = totTotal + total;
    // display the results of purchase
    JOptionPane.showMessageDialog( null, "Amount: " + value +
    "\nTax: " + tax + "\nTotal: " + total, "Sale", JOptionPane.INFORMATION_MESSAGE );
    // get next code from user
    itemString = JOptionPane.showInputDialog(
    "Enter item code:" );
    // If sentinel value reached
    if ( item == 999 ) {
    // display the daily totals
    JOptionPane.showMessageDialog( null, "Total amount of items sold today: " + quantity +
    "\nValue of ites sold today: " + totValue + "\nTotal tax collected today: " + totTax +
    "\nTotal Amount collected today: " + totTotal, "Totals", JOptionPane.INFORMATION_MESSAGE );
    System.exit( 0 ); // terminate application
    } // end sentinel
    } // end message
    } // end class Sales

    Here you go. I haven't tested this but it does compile. I've put in a 'few helpful hints'.
    import java.text.NumberFormat; // class for numeric formating from page 178
    import javax.swing.JOptionPane; // class for JOptionOPane
    public class TestTextFind {
    //main method begins execution ofJava Application
    public static void main( String args[] )
         double quantity; // total of items purchased
         double tax; // total of tax
         double value; // total cost of all items before tax
         double total; // total of items including tax
    //     double totValue; // daily value counter
    //     double totTax; // daily tax counter
    //     double totTotal; // daily total amount collected (+tax) counter
    // Always initialise your numbers unless you have a good reason not too
         double totValue = 0; // daily value counter
         double totTax = 0; // daily tax counter
         double totTotal = 0; // daily total amount collected (+tax) counter
         double itemCode;
         double item = 0;
         String itemCodeString; // item code entered by user
         String quantityString; // quantity entered by user
         // initialization phase
         quantity = 0; // initialize counter for items purchased
         // get first code from user
         itemCodeString = JOptionPane.showInputDialog("Enter item code:" );
         // convert itemString to double
         itemCode = Double.parseDouble ( itemCodeString );
         // loop until sentinel value read from user
         while ( itemCode != 999 ) {
    * 1. variable item mightnot have been initialised
    * You had item and itemCode the wrong way round.
    * You are supposed to be checking itemCode but setting the value
    * for item
              // converting code to amount using if statements
              if ( item == 100 )
              {itemCode = 2.98;}
              else if ( item == 200 )
              {itemCode = 4.50;}
              else if ( item == 300 )
              {itemCode = 6.79;}
              else if ( item == 400 )
              {itemCode = 5.29;}
              else if ( item == 500 )
              {itemCode = 7.20;}
              else {//if invalid code entered, output message
                   JOptionPane.showMessageDialog( null, "Invalid code entered, please try again!",
                   "Item Code", JOptionPane.INFORMATION_MESSAGE );
              } // end if
         } // end while
         // get quantity of item user
         itemCodeString = JOptionPane.showInputDialog("Enter quantity:" );
    * 2.
    * You have declared quantityString here but you never give it a value.
    * I think this should be itemCodeString shouldnt it???
    * Or should you change itemCodeString above to quantityString?
         // convert quantityString to int
    //     quantity = Double.parseDouble ( quantityString );  // old code
         quantity = Double.parseDouble ( itemCodeString );
         // add quantity to quantity
         quantity = quantity + quantity;
         // calculation time! value
         value = quantity * itemCode;
         // calc tax
         tax = value * .07;
         // calc total
         total = tax + value;
         //add totals to counter
    * 3. 4. and 5.
    * With the following you have not assigned the 'total' variables a value
    * so in effect you are saying eg. "total = null + 10". Thats why an error is
    * raised.  If you look at your declaration i have assigned them an initial
    * value of 0.
         totValue = totValue + value;
         totTax = totTax + tax;
         totTotal = totTotal + total;
         // display the results of purchase
         JOptionPane.showMessageDialog( null, "Amount: " + value +
         "\nTax: " + tax + "\nTotal: " + total, "Sale", JOptionPane.INFORMATION_MESSAGE );
         // get next code from user
         itemCodeString = JOptionPane.showInputDialog("Enter item code:" );
         // If sentinel value reached
         if ( itemCode == 999 ) {
              // display the daily totals
              JOptionPane.showMessageDialog( null, "Total amount of items sold today: " + quantity +
              "\nValue of ites sold today: " + totValue + "\nTotal tax collected today: " + totTax +
              "\nTotal Amount collected today: " + totTotal, "Totals",           JOptionPane.INFORMATION_MESSAGE );
              System.exit( 0 ); // terminate application
         } // end sentinel
    } // end message
    } // end class SalesRob.

  • Need some help with code.. No idea what's wrong! I'm new..(J2ME related)

    Hey there,
    I've just started programming J2ME using Netbeans using the java mobility pack, trying to create a program which interacts with a php webserver..
    I created some code which accessed my php script on my server and returned the contents of the page back, and successfully got it working. However, i did a bit of treaking, and then tried to remove it all.. and now my code won't work. I've been examining it for a good hour and can't seem to find the error! It's annoying me pretty badly.. I'm not liking J2ME already.
    Could someone please look at my code and help me out? I really really want to get this working..
    * VisualMidlet.java
    * Created on 26 October 2007, 19:37
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    * @author Will
    public class VisualMidlet extends MIDlet{
    /** Creates a new instance of VisualMidlet */
    private Display display;
    private Command Submit;
    private Command okCommand2;
    private Command Submit1;
    private Form Form1;
    private StringItem stringItem1;
    String url = "http://people.bath.ac.uk/wal20/testGET.php?type=3";
    public VisualMidlet() {
    System.out.println("initialized");
    display = Display.getDisplay(this);
    Connect();
    public void startApp() {
    public void Connect(){
    try {getViaStreamConnection(url);}
    catch (IOException e) {
    System.out.println("IOException " + e);
    e.printStackTrace();
    public void getViaStreamConnection(String url) throws IOException {
    StreamConnection streamConnection = null; //declares a stream connection
    InputStream inputStream = null; // declares an input Stream
    StringBuffer b = new StringBuffer();
    TextBox textBox = null;
    try {
    System.out.println("Establishing stream");
    streamConnection = (StreamConnection)Connector.open(url);
    System.out.println("Stream established");
    inputStream = streamConnection.openInputStream();
    int ch;
    while((ch = inputStream.read()) != -1) {
    b.append((char) ch);
    textBox = new TextBox("Simple URL Fetch", b.toString(), 1024, 0);
    } finally {
    if(inputStream != null) {
    inputStream.close();
    if(streamConnection != null) {
    streamConnection.close();
    display.setCurrent(textBox);
    public void pauseApp() {   }
    public void destroyApp(boolean unconditional) {  }
    /** This method initializes UI of the application.
    private void initialize() {                     
    getDisplay().setCurrent(get_Form1());
    * This method should return an instance of the display.
    public Display getDisplay() {                        
    return Display.getDisplay(this);
    * This method should exit the midlet.
    public void exitMIDlet() {                        
    getDisplay().setCurrent(null);
    destroyApp(true);
    notifyDestroyed();
    /** This method returns instance for Submit component and should be called instead of accessing Submit field directly.
    * @return Instance for Submit component
    public Command get_Submit() {
    if (Submit == null) {                     
    // Insert pre-init code here
    Submit = new Command("Submit", Command.OK, 1);
    // Insert post-init code here
    return Submit;
    /** This method returns instance for okCommand2 component and should be called instead of accessing okCommand2 field directly.
    * @return Instance for okCommand2 component
    public Command get_okCommand2() {
    if (okCommand2 == null) {                     
    // Insert pre-init code here
    okCommand2 = new Command("Ok", Command.OK, 1);
    // Insert post-init code here
    return okCommand2;
    /** This method returns instance for Submit1 component and should be called instead of accessing Submit1 field directly.
    * @return Instance for Submit1 component
    public Command get_Submit1() {
    if (Submit1 == null) {                      
    // Insert pre-init code here
    Submit1 = new Command("Submit", Command.OK, 1);
    // Insert post-init code here
    return Submit1;
    /** This method returns instance for Form1 component and should be called instead of accessing Form1 field directly.
    * @return Instance for Form1 component
    public Form get_Form1() {
    if (Form1 == null) {                     
    // Insert pre-init code here
    Form1 = new Form(null, new Item[] {get_stringItem1()});
    // Insert post-init code here
    return Form1;
    /** This method returns instance for stringItem1 component and should be called instead of accessing stringItem1 field directly.
    * @return Instance for stringItem1 component
    the code for the php script is:
    <?php
    $response = "Hello";
    if (isset($_GET)) {
    switch ($_GET["type"]) {
    case 1: $response = "Good Morning"; break;
    case 2: $response = "Good Afternoon"; break;
    case 3: $response = "Good Evening"; break;
    default: $response = "Hello"; break;
    echo $response;
    ?>
    I would be grateful for any reply
    Thank you in advance
    -Will

    sorry! i'll repost the code in code format
    * VisualMidlet.java
    * Created on 26 October 2007, 19:37
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    * @author Will
    public class VisualMidlet extends MIDlet{
    /** Creates a new instance of VisualMidlet */
    private Display display;
    private Command Submit;
    private Command okCommand2;
    private Command Submit1;
    private Form Form1;
    private StringItem stringItem1;
    String url = "http://people.bath.ac.uk/wal20/testGET.php?type=3";
    public VisualMidlet() {
    System.out.println("initialized");
    display = Display.getDisplay(this);
    Connect();
    public void startApp() {
    public void Connect(){
    try {getViaStreamConnection(url);}
    catch (IOException e) {
    System.out.println("IOException " + e);
    e.printStackTrace();
    public void getViaStreamConnection(String url) throws IOException {
    StreamConnection streamConnection = null; //declares a stream connection
    InputStream inputStream = null; // declares an input Stream
    StringBuffer b = new StringBuffer();
    TextBox textBox = null;
    try {
    System.out.println("Establishing stream");
    streamConnection = (StreamConnection)Connector.open(url);
    System.out.println("Stream established");
    inputStream = streamConnection.openInputStream();
    int ch;
    while((ch = inputStream.read()) != -1) {
    b.append((char) ch);
    textBox = new TextBox("Simple URL Fetch", b.toString(), 1024, 0);
    } finally {
    if(inputStream != null) {
    inputStream.close();
    if(streamConnection != null) {
    streamConnection.close();
    display.setCurrent(textBox);
    public void pauseApp() { }
    public void destroyApp(boolean unconditional) { }
    /** This method initializes UI of the application.
    private void initialize() {
    getDisplay().setCurrent(get_Form1());
    * This method should return an instance of the display.
    public Display getDisplay() {
    return Display.getDisplay(this);
    * This method should exit the midlet.
    public void exitMIDlet() {
    getDisplay().setCurrent(null);
    destroyApp(true);
    notifyDestroyed();
    /** This method returns instance for Submit component and should be called instead of accessing Submit field directly.
    * @return Instance for Submit component
    public Command get_Submit() {
    if (Submit == null) {
    // Insert pre-init code here
    Submit = new Command("Submit", Command.OK, 1);
    // Insert post-init code here
    return Submit;
    /** This method returns instance for okCommand2 component and should be called instead of accessing okCommand2 field directly.
    * @return Instance for okCommand2 component
    public Command get_okCommand2() {
    if (okCommand2 == null) {
    // Insert pre-init code here
    okCommand2 = new Command("Ok", Command.OK, 1);
    // Insert post-init code here
    return okCommand2;
    /** This method returns instance for Submit1 component and should be called instead of accessing Submit1 field directly.
    * @return Instance for Submit1 component
    public Command get_Submit1() {
    if (Submit1 == null) {
    // Insert pre-init code here
    Submit1 = new Command("Submit", Command.OK, 1);
    // Insert post-init code here
    return Submit1;
    /** This method returns instance for Form1 component and should be called instead of accessing Form1 field directly.
    * @return Instance for Form1 component
    public Form get_Form1() {
    if (Form1 == null) {
    // Insert pre-init code here
    Form1 = new Form(null, new Item[] {get_stringItem1()});
    // Insert post-init code here
    return Form1;
    /** This method returns instance for stringItem1 component and should be called instead of accessing stringItem1 field directly.
    * @return Instance for stringItem1 component
    }

  • Help in code,, please !!

    Hi all,
    I want help in my code ..
    I am doing chat system and the client show register before they login to the chat ..
    after they register, they should login ..
    I want to add the client's name with the others client's name to the ChatGUI but I don't know where the error with me ..
    This is my code ..
    *try {*
    *                Class.forName("com.mysql.jdbc.Driver");*
    *                connection = DriverManager.getConnection(URL,username,password);*
    *                Statement statement = connection.createStatement();*
    *                ResultSet resultSet;*
    *               String query = "SELECT * FROM users WHERE Name ='"+jTextField1.getText()+"' AND Password = '"+jPasswordField1.getText()+"' ";*
    *                    resultSet= statement.executeQuery(query);     *
    *                    if(resultSet.next()){*
    *                    String name= resultSet.getString(2);*
    *                    secwindow ss = new secwindow();*
    *                   ss.setVisible(true);*
    *                   ss.users. /// here I don'i know what i should put to list the name with the other*
    *                    else{*
    *                         System.out.println("no user found");*
    *                         M m =new M();     *
    *                         m.setVisible(true);*
    *                    } catch (Exception b2) {*
    *                    b2.printStackTrace();*
    Can anyone help me please ?

    aseert.af wrote:
    I want help in my code ..
    I have to put in my two cents here because this bugs me. When getting free help, it's rude to give stipulations on that help. We're all volunteers here, remember? If you really must demand a certain type of help, then you should pay for it, simple as that.

  • Need some help on code

    hello all.
    i have some errors in my code.
    the errors are:
    java.net.MalformedURLException
            at java.net.URL.<init>(URL.java:601)
            at java.net.URL.<init>(URL.java:464)
            at java.net.URL.<init>(URL.java:413)
            at work2.LinksExtractor.<init>(LinksExtractor.java:95)
            at work2.TestWorkerThread.run(TestWorkerThread.java:35)
            at work2.WorkerThread.run(ThreadPool.java:150)
    java.net.MalformedURLException
            at java.net.URL.<init>(URL.java:601)
            at java.net.URL.<init>(URL.java:464)
            at java.net.URL.<init>(URL.java:413)
            at work2.LinksExtractor.<init>(LinksExtractor.java:95)
            at work2.TestWorkerThread.run(TestWorkerThread.java:35)
            at work2.WorkerThread.run(ThreadPool.java:150)
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
            at work2.spy.printLinks(spy.java:108)
            at work2.spy.shearch(spy.java:77)
            at work2.spy.main(spy.java:42)in my code i created a thread pool and wrote the run function. in the program I tryed to find all the links in the page,and the threads are take care of that link.
    thanks alot!
    /*   finding all the links in the str and calling page function to calculate the statistic of the shearchWord*/
    private static void printLinks(String str,String shearchWord,URL u) {
    ThreadPool pool = new ThreadPool(10);
        //ArrayList of saving the results of statistic and the link
        ArrayList<linkerCount> list = new ArrayList<linkerCount>();
        try {
             //Thread[]   threads = new Thread[Global.numOfThreads];
              LinksExtractor extractor = new LinksExtractor(u);
              String[] propsToExtract = new String[] {"href"};
    // to know that is the length propsToExtract.length
              for(int i=0;i<10;i++) {
                   //call the extract method with property as argument
                   //get the Iterator from ArrayList which returned by the method
                   Iterator<URL> iterator = extractor.extract(propsToExtract).iterator();
                   //iterate through results
                   while(iterator.hasNext()) {
                        //print every result
                        //System.out.println(iterator.next().toString());
                        pool.assign(new TestWorkerThread(iterator.next().toString()));
    pool.complete();
    System.out.println(printLinkerCount(Global.list));
                             // threadsClass threads[j] = new threadsClass(iterator.next().toString());
                             // threads[j].start();
    // threadsClass t=new threadsClass(iterator.next().toString());
    // t.start();
    // System.out.print(printLinkerCount(list));
              // if (page(str.substring(start,startText),shearchWord)!=null)
         // list.add(page(str.substring(start,startText),shearchWord));
         catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
    package work2;
    import java.util.*;
    * Java Thread Pool
    * This is the main class for the thread pool. You should
    * create an instance of this class and assign tasks to it.
    * @version 1.0
    public class ThreadPool {
    * The threads in the pool.
    protected Thread threads[] = null;
    * The backlog of assignments, which are waiting
    * for the thread pool.
    Collection assignments = new ArrayList(3);
    * A Done object that is used to track when the
    * thread pool is done, that is has no more work
    * to perform.
    protected Done done = new Done();
    * The constructor.
    * @param size How many threads in the thread pool.
    public ThreadPool(int size)
    threads = new WorkerThread[size];
    for (int i=0;i<threads.length;i++) {
    threads[i] = new WorkerThread(this);
    threads[i].start();
    * Add a task to the thread pool. Any class
    * which implements the Runnable interface
    * may be assienged. When this task runs, its
    * run method will be called.
    * @param r An object that implements the Runnable interface
    public synchronized void assign(Runnable r)
    done.workerBegin();
    assignments.add(r);
    notify();
    * Get a new work assignment.
    * @return A new assignment
    public synchronized Runnable getAssignment()
    try {
    while ( !assignments.iterator().hasNext() )
    wait();
    Runnable r = (Runnable)assignments.iterator().next();
    assignments.remove(r);
    return r;
    } catch (InterruptedException e) {
    done.workerEnd();
    return null;
    * Called to block the current thread until
    * the thread pool has no more work.
    public void complete()
    done.waitBegin();
    done.waitDone();
    protected void finalize()
    done.reset();
    for (int i=0;i<threads.length;i++) {
    threads[i].interrupt();
    done.workerBegin();
    threads[i].destroy();
    done.waitDone();
    * The worker threads that make up the thread pool.
    * @author Jeff Heaton
    * @version 1.0
    class WorkerThread extends Thread {
    * True if this thread is currently processing.
    public boolean busy;
    * The thread pool that this object belongs to.
    public ThreadPool owner;
    * The constructor.
    * @param o the thread pool
    WorkerThread(ThreadPool o)
    owner = o;
    * Scan for and execute tasks.
    public void run()
    Runnable target = null;
    do {
    target = owner.getAssignment();
    if (target!=null) {
    target.run();
    owner.done.workerEnd();
    } while (target!=null);
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package work2;
    import java.io.IOException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Iterator;
    * @author vitaly87
    */public class TestWorkerThread implements Runnable {
    static private int count = 0;
    String link;// the links to shearch in
    private int taskNumber;
    protected Done done;
    * @param done
    TestWorkerThread(String link)
    link=this.link;
    count++;
    taskNumber = count;
    public void run()
    try{
              LinksExtractor extractor = new LinksExtractor(this.link);
         String[] propsToExtract = new String[] {"href"};
         for(int i=0;i<propsToExtract.length;i++) {
              //call the extract method with property as argument
              //get the Iterator from ArrayList which returned by the method
              Iterator<URL> iterator = extractor.extract(propsToExtract[i]).iterator();
              //iterate through results
              while(iterator.hasNext()){
                   synchronized(this) {
                   Global.list.add(spy.newPage(iterator.next().toString(),Global.shearchWord));
    }catch(IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    try {
    Thread.sleep((int)(Math.random()*500));
    } catch (InterruptedException b) {

    ok the line 42 is,
    target= in.readLine();
    i thinks its because the thread pool all the errors,but i dont sure. here is the "main things in the" class spy.java. I am sorry if the code is too long.hope you can help me:)
    the main function is shearch.
    the spy.java is:
    public class spy {
    public static void main(String[] args) {
    String target = null;
        try
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("write the shearch word:");
        target= in.readLine();
        //System.out.println("wait for the result");
        shearch(target);
        catch(IOException e)
             System.out.println("IOException has been caught");
    /*  function that get a word to search  web . */
    public static void shearch(String target) {
    target = target.trim( );
    Global.shearchWord=target;
    QueryString query = new QueryString("search", target);
    try
    {//Open the URL for reading
        URL u = new URL("http://search.dmoz.org/cgi-bin/search?search=" + query);
    String str="";
           // buffer the input to increase performance
        InputStream in = new BufferedInputStream(u.openStream());
        // chain the InputStream to a Reader
        InputStreamReader theHTML = new InputStreamReader(in);
       //System.out.print(StreamToString(theHTML));
    //str is string of the converse of the Html
        str=StreamToString(theHTML);
        printLinks(str,target,u);
        //System.out.println(str);
    catch (MalformedURLException e)
        System.err.println(e);
    catch (IOException e)
        System.err.println(e);
    /*   finding all the links in the str and calling page function to calculate the statistic of the shearchWord*/
    private static void printLinks(String str,String shearchWord,URL u) {
    ThreadPool pool = new ThreadPool(10);
        //ArrayList of saving the results of statistic and the link
        ArrayList<linkerCount> list = new ArrayList<linkerCount>();
        try {
             //Thread[]   threads = new Thread[Global.numOfThreads];
              LinksExtractor extractor = new LinksExtractor(u);
              String[] propsToExtract = new String[] {"href"};
    // to know that is the length propsToExtract.length
              for(int i=0;i<propsToExtract.length;i++) {
                   //call the extract method with property as argument
                   //get the Iterator from ArrayList which returned by the method
                   Iterator<URL> iterator = extractor.extract(propsToExtract).iterator();
                   //iterate through results
                   while(iterator.hasNext()) {
                        //print every result
                        //System.out.println(iterator.next().toString());
                        pool.assign(new TestWorkerThread(iterator.next().toString()));
    pool.complete();
    Global.deleteDuplicate();
    System.out.println(printLinkerCount(Global.list));
                             // threadsClass threads[j] = new threadsClass(iterator.next().toString());
                             // threads[j].start();
    // threadsClass t=new threadsClass(iterator.next().toString());
    // t.start();
    // System.out.print(printLinkerCount(list));
              // if (page(str.substring(start,startText),shearchWord)!=null)
         // list.add(page(str.substring(start,startText),shearchWord));
         catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
    //finding all the links in the page
    /*get the ArrayList and return a sorrting array list */
    private static ArrayList<linkerCount> printLinkerCount( ArrayList<linkerCount> list) {
    double max;
    int index=0;
    ArrayList<linkerCount> finalList = new ArrayList<linkerCount>();
    for(int i=0;list.size()>i;i++ ){
         max=(double) ((linkerCount) list.get(i)).getCount();
         index=i;
         if (max!=-1){
              for(int j=0;list.size()>j;j++ )
                   if ((double) ((linkerCount) list.get(j)).getCount()!=-1)
                   if (max-(double) ((linkerCount) list.get(j)).getCount()<0)
                   {index=j;
                   max=(double) ((linkerCount) list.get(j)).getCount();}
                   if (j+1==list.size()) {
                        finalList.add(linkerCount.getNewLinkerCount(max,((linkerCount) list.get(index)).getLink()));
    System.out.println(max+((linkerCount) list.get(index)).getLink());
                        ((linkerCount) list.get(index)).setCount(-1);
    return finalList;
    /* get the links and the word. trying to find that word in the page.
    * the function return the links and the statistics */
    static linkerCount newPage(String link,String word) {
         String str = new String();
    try
    {//Open the URL for reading
    URL u = new URL(link);
    // TODO Auto-generated method stub
    // buffer the input to increase performance
    InputStream in = new BufferedInputStream(u.openStream());
    // chain the InputStream to a Reader
    InputStreamReader theHTML = new InputStreamReader(in);
    str=StreamToString(theHTML);
    //get of all the html tags
    str = str.replaceAll("\\<.*?\\>", "");
    theHTML.close();
    //System.out.println(statistic+link);
    catch (MalformedURLException e)
    System.err.println(e);
    catch (IOException e)
    System.err.println(e);
    }double statistic;
    if (countWord(str)!=0)
    statistic=(double)countSubString(str,word)/countWord(str);
    } else statistic=0;
    //inserting the link and the statistic to listArray
    linkerCount s=new linkerCount(link,statistic);
    //System.out.println(statistic+link);
    return s;
    Edited by: vitaly87 on Apr 9, 2010 9:24 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Why can't I get this extension to show up after I download it, help with code?

    Is there an error in the source code somwhere, here is the url https://addons.mozilla.org/en-US/firefox/addon/wisecampus-1/. I created this extension with the app builder where it generates a zip and you modify it to what you want. I made very little changes, I just would like to have a button on the toolbar that launches the site when clicked. If someone with more experience could take a look at the source code and possibly help me get this up and running it would be greatly appreciated. Thanks all!

    Not really a Firefox user support issue. I am not am add-on developer, but I think I found your problem. ''Can't show the actual css code from that file, this forum software would try to execute it instead of displaying the code.''
    In the '''overlay.css''' file the '''''wcextension-toolbar-button - list-style-image''''' shows the '''''url''''' as http://www.wisecampusbooks.com/images/WC_icon2.jpg . Shouldn't it point to the '''toolbar-button.png''' image in the \chrome\skin\ folder instead?
    I can see the image from that URL when the toolbar button is sitting in the Customize Palette, but the image disappears when the button is moved to a Toolbar. I think that using a web based image in the UI is a security fault, which Firefox is blocking. Something like that could potentially be used to "track" a user or to count how often that button is clicked.
    ''BTW'' the Add-ons support forum is here: <br />
    https://forums.mozilla.org/addons/ <br />
    or you could post here, if you need additional help <br />
    http://forums.mozillazine.org/viewforum.php?f=53&sid=554d097b5d69110d4859bd054051b9b2

  • Need help with code for adding dates to form

    Hello forum goers
    I'm new to making forms and figured out how to auto add the date, however I need the form to change the date for every copy made.
    For example today is 06/08/2012 if I print 10 copies of the form it will output 10 pages ranging from 06/08/2012 to 06/17/2012. If code exists to do this I would be very gratefull to whoever helps, I also wouldn't mind if that is not possible for manually inputing the start / end dates.
    Currently I print 15-30 copies of the form and hand write each of the dates but I'm just getting to busy to do that. I also cannot print one a day it must be in batches.
    Thanks in advanced.

    What you are asking for is more complex than just setting the current date. Each time the form prints it has to know that it has to change the date. I would suggest doing this.
    First, setup a document level script to set the date to the current date. I suspect that you have already done this?
    Next, Create a "DidPrint" document action to increment the date.  To do this the script will need to scan the current text value of the date, add one day to it, and then reformat it.  You'll find information on this type of scripting in these articles:
    http://acrobatusers.com/tutorials/working-with-date-and-time-in-acrobat-javascr
    ipt
    http://acrobatusers.com/tutorials/working-with-date-and-time-in-acrobat-javascr
    ipt-part-2
    http://acrobatusers.com/tutorials/working-with-date-and-time-in-acrobat-javascr
    ipt-part-3
    Since the increment happenes in the Did Print you will need to print each copy individually. If you enter 10 copies in the print dialog it won't work. You have to print one at a time.  You can automate this activity with a console script.
    One of the advantages of incrementing in the DidPrint is that you can also manually enter a date and it will increment from there.
    Thom Parker
    The source for PDF Scripting Info
    pdfscripting.com
    The Acrobat JavaScript Reference, Use it Early and Often
    Then most important JavaScript Development tool in Acrobat
    The Console Window (Video tutorial)
    The Console Window(article)
    Having trouble, Why Doesn't my Script Work?

Maybe you are looking for