Need help with binary numbers

hey i'm doing some things, but i need a entry of a binary coded number, i know that an hex number is written like 0xFF but how do i put a binary number in an instruction such as:
byte b
b="binary number"

I see what you want to do, but you can only do this with octal and hex. With binary, you would have to do it something like this:
byte b = Byte.parseByte("01101001", 2); // base-2

Similar Messages

  • 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 help with random numbers

    hi i need to generate 2 random numbers from array list . and then take out that two numbers from list.
         String[] plcard = { "AC", "KC", "QC", "JC",
              "10C", "9C", "8C", "7C","6C","5C","4C","3C","2C", "AD", "KD", "QD", "JD",
              "10D", "9D", "8D", "7D","6D","5D","4D","3D","2D", "AS", "KS", "QS", "JS",
              "10S", "9S", "8S", "7S","6S","5S","4S","3S","2S", "AH", "KH", "QH", "JH",
              "10H", "9H", "8H", "7H","6H","5H","4H","3H","2H",};
    this is the list if someone can help me i would appreciate
    thanks in advance

    haha, never noticed the .shuffle(List) method!
    maybe java is getting too convenient (just kidding)?
    i never wrote a card game.
    how would the more programmingly gifted of us do this?
    this is my shot at it for what its worth...
    public class Card{
    public Card(int rank, int suit){
    this.rank = rank;
    this.suit = suit;
    int rank (or String i suppose)
    int suit;
    static final club = 1;
    static final spade = 2;
    static final heart = 3;
    static final diamond = 4;
    public class Shuffler{
    public Shuffler(){
    int NumOfDecks = 1;
    Vector ShuffledDeck;
    // num of decks
    for(int i = 0; i < NumOfDecks){
    // 4 suits
    for(int j = 0; j < 4; j++){
    // 13 ranks
    for(int k = 0; k < 13; k++){
    ShuffledDeck.add(new Card(k, j));
    } // suits
    } // num of decks
    Collections.shuffle(ShuffledDeck);
    // Done?
    }

  • Need help with skype numbers....urgent please!

    Question regarding skype numbers..... So i plan to buy hongkong skype number,......say for example + 852 8192 6362, and if im right , i can receive the calls on my PC /desktop, etc. But what about if im traveling , for few days to mainland china or london , will my family still be able to call the same number with appropriate county code, n will i continue to recive calls on my PC. { *Example calling me in china +8621 8192 6362 } In short, can my family call my anywhere in the world by using proper country codes, or is skype number limited to hongkong only, I travel alot, and cant change numbers frequently. Thanks....

    Hi, ajamal786, and welcome to the Community,
    Yes, your one Skype Number travels with your account regardless of wherever you are.  Such is the beauty of a Skype Number: people can call you on the number you set up, which in theory would be a local call to them depending upon the availability of numbers from which you can choose (my Skype Number exchange is a few townships away, but still a local call), and reach you on Skype.
    So, no need to change a Skype Number.
    Elaine
    Was your question answered? Please click on the Accept as a Solution link so everyone can quickly find what works! Like a post or want to say, "Thank You" - ?? Click on the Kudos button!
    Trustworthy information: Brian Krebs: 3 Basic Rules for Online Safety and Consumer Reports: Guide to Internet Security Online Safety Tip: Change your passwords often!

  • I need help with the numbering pages in a book file

    I have a 53 chapter book that which each chapter is its own document. It used to work great. The page numbers of each document used to continue from the last page number of the previous document. That was until today when I opened it and all the page numbers now start at one. I don't know what to do. I have checked all of the options I knew to check. Each document still has the 'automatic page numbering' option selected. I truly don't want to have to go through and manully renumber every document. It will take time I do not have. If I can get somebody's help, it would be wonderful.

    Nor do I. It sounds like everything is set correctly. You might want to try creating a new Book file and add the individaul documents into it and see if that fixes things. Also, have you tried updating the numberingfrom the menu since this started?

  • Need help with formating numbers

    public void returnDollars()
              double dollar;
              dollar=amountr-amount;
    NumberFormat fmt = NumberFormat.getNumberInstance();
              System.out.println(fmt.fomat(dollar));
    there is my code.....now lets say
    amountr = 10
    amount 8.5
    now when i print my dollar amount i want it to show up as 1 not 1.5 or 2. So in other words format it with no decimals and not round up at the same time.
    Help would be appriciated...thanks

    well...after 8 hours of trying to get it working i did it.....here it is ...........I'm sure there are many ways to make it smaller.
    import java.text.*;
    import java.io.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    public class Cashier
    double amount;
    double amountr;
    double dollar;
    double amountleft;
    double quaters;
    double test;
    double dimes;
    double pennies;
    public void getAmount()throws IOException
         BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("Please enter amount due:");
              String input = console.readLine();
         amount = Double.parseDouble(input);
    System.out.println("Amount due = " + amount);
         public void recieve()throws IOException
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("Please enter amount recieved :");
              String input = console.readLine();
         amountr = Double.parseDouble(input);
    System.out.println("Amount recieved = " + amountr);
         public void returnDollars()throws IOException
              double check = amountr-amount;
              dollar=amountr-amount;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)dollar);
    double d = Double.valueOf(s).doubleValue();
    amountleft=check-d;
         System.out.println("Dollars to return " + s);
    public void returnQuaters()
         quaters= amountleft/.25;
         double check = quaters;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)quaters);
    double d = Double.valueOf(s).doubleValue();
    fmt.setMaximumFractionDigits(2);
    String dol = fmt.format(amountleft);
              //System.out.println(dol);
              double e =Double.valueOf(dol).doubleValue();
    e= e-2*(.25);
    amountleft=e;
         System.out.println("Quaters to return: " + s);
         public void returnDimes()
         dimes= amountleft/.1;
         double check = dimes;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)dimes);
    System.out.println("Dimes to return: " + s);
    double d = Double.valueOf(s).doubleValue();
    fmt.setMaximumFractionDigits(2);
    String dol = fmt.format(amountleft);
              double e =Double.valueOf(dol).doubleValue();
    e= e-1*(.1);
    fmt.setMaximumFractionDigits(2);
    String dola = fmt.format(e);
              double t =Double.valueOf(dola).doubleValue();
    amountleft=t;
              public void returnNickles()
         double nickles = amountleft/.05;
              double check = nickles;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)nickles);
    System.out.println("Niclkles to return: " + s);
    double d = Double.valueOf(s).doubleValue();
    fmt.setMaximumFractionDigits(2);
    String dol = fmt.format(amountleft);
              double e =Double.valueOf(dol).doubleValue();
    e= e-1*(.05);
    fmt.setMaximumFractionDigits(2);
    String dola = fmt.format(e);
              double t =Double.valueOf(dola).doubleValue();
    amountleft=t;
         public void returnPennies()
              double pennies = amountleft/.01;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)pennies);
    System.out.println("Pennies to return: " + s);
         public static void main(String[] a) throws IOException
              Cashier cash = new Cashier();
              cash.getAmount();
              cash.recieve();
              cash.returnDollars();
              cash.returnQuaters();
              cash.returnDimes();
              cash.returnNickles();
              cash.returnPennies();

  • Need help with rounding numbers in Java

    I finally have this program to where it needs to be except for one thing. The variable "freetime" isn't showing any kind of output in the applet. The variable sum and freetime are both called at the start of the program, and have equations to figure out the output for them, but only sum shows an output. I tried using brackets as opposed to multiple parentheses. What can I do to fix this so that there is an output? I was thinking of using something to round up the result, but I can't figure it out. Can anyone help?
    import java.awt.*;
    import javax.swing.*;
    public class FinalLab extends JApplet{
    String firstNum, secondNum, thirdNum, fourthNum, fifthNum;
    int personal, family, school, work, sleep, sum, freetime;
    public void init()
    String firstNum, secondNum, thirdNum, fourthNum, fifthNum;
    firstNum = JOptionPane.showInputDialog( "Enter total personal hours." );
    secondNum = JOptionPane.showInputDialog( "Enter total family hours." );
    thirdNum = JOptionPane.showInputDialog( "Enter total school hours." );
    fourthNum = JOptionPane.showInputDialog( "Enter total work hours." );
    fifthNum = JOptionPane.showInputDialog( "Enter total sleep hours." );
    personal = Integer.parseInt( firstNum );
    family = Integer.parseInt( secondNum );
    school = Integer.parseInt( thirdNum );
    work = Integer.parseInt( fourthNum );
    sleep = Integer.parseInt( fifthNum );
    sum = (personal + family + school + work + sleep);
    freetime = ((168-sum)/168)*100;
    public void paint(Graphics g) {
    super.paint( g );
    g.drawRect( 15, 10, 270, 20 );
    g.drawRect( 15, 35, 270, 20 );
    g.drawRect( 15, 60, 270, 20 );
    g.drawRect( 15, 85, 270, 20 );
    g.drawRect( 15, 110, 270, 20 );
    g.drawRect( 15, 135, 270, 20 );
    g.drawRect( 15, 160, 270, 20 );
    g.drawString( "Personal hours: " + personal, 25, 25);
    g.drawString( "Family hours: " + family, 25, 50);
    g.drawString( "School hours: " + school, 25, 75);
    g.drawString( "Work hours: " + work, 25, 100);
    g.drawString( "Sleep hours: " + sleep, 25, 125);
    g.drawString( "Total hours: " + sum, 25, 150);
    g.drawString( "Free time: " + freetime, 25, 175);
    }

    I am guessing that you really meant that you are seeing "Free time: 0" instead of what you said, which was that it wasn't showing any kind of output. (Your whole terminology is weird, you don't "call a variable" just for example.) If that's the case, it's because you are using integer division. You'll find that 27/168, for example, gives zero. I don't know why you are multiplying by 100 in your calculation and doing the division, perhaps you meant to return the free time as a percentage (in which case your output should say that), but since you are doing that you could do it this way:((168-sum)*100/168)Then you are doing 2700/168, which produces a reasonable number.

  • Need help with a Numbers (ISBLANK) formula

    Having trouble with a cell formula that tests 2 cells for blank condition.
    I want to sum 2 cells only if they are BOTH blank.  (Trying to eliminate the
    "0" in the sum cell if both test cells are blank.)
    I've tried using ISBLANK, AND, IF functions but no success.
    Would appreciate your help on this. Thank you.

    Hi there.
    Perhaps due to my bad english, I could not understand your question, but I want to help, anyway.
    The question is: why would you want to sum two blank cells? Or what you want is to sum two cells IF two different cells are blank?
    Best regards,
    Otávio

  • Need help with my numbers app synching with icloud

    My numbers app just stopped synching with icloud and my ipad2. And vice versa. I deleted then reinstalled the app, synched the phone, etc. and it still won't transfer to iclous. Any suggestions?

    Find your serial number quickly
    Sign in, activation, or connection errors | CS5.5 and later, Acrobat DC
    Mylenium

  • Need Help with random numbers, please help

    Hi guys;
    I need your help for a school project. I need to generate a random number from 1.0 to 2.0. How would I do that?
    Regards,

    http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html#nextFloat()

  • Need help with a numbers formula

    Hi I am looking for the formula in numbers to do the following apologies if I havn't explained this properly:
    if I x is greater than y subtract z
    eg
    if A2 is greater than 7 subtract 1..... so if A2 was 9 B2 would be 8 but if A2 was 6 B2 would be 6

    Hi tick,
    As I read your statement, x is the numer in column A, x is a constant placed either in the formula or in a separate cell (not A or B), and z is the result in column B.
    This example uses the constant 7, placed in a separate table:
    Formula in column B:
    =IF(A>Table 2::$A$2,A-1,A)
    Here, the constant is written into the formula:
    Formula in column B:
    =IF(A>7,A-1,A)
    Regards,
    Barry

  • Need help with complex numbers ..

    Hi!
    Just want to check if i got it right - if anyone could pls confirm:
    public void divComplex(Complex a, Complex b)
    x = ((a.x * b.x) + (a.y * b.y))/((b.x * b.x) + (b.y * b.y));
    y = ((a.y * b.x) + (a.x * b.x))/((b.x * b.x) + (b.y * b.y));
    public void multComplex(Complex a, Complex b)
    x = ((a.x * b.x) - (a.y * b.y));
    y = ((a.x * b.y) + (a.y * b.x));
    where:
    protected double x;
    protected double y;
    is declared to represent the complex number .
    Is this correct?
    Siw

    For the division you have,
    a/b = a*b'/b*b' = a*b'/|b|
    |b| = (b.x + ib.y)*(b.x - ib.y) = b.x*b.x + b.y*b.y
    a*b' = (a.x + ia.y)*(b.x - ib.y) =
    (a.x*b.x + a.y*b.y) + i(a.y*b.x - a.x*b.y)
    There seems to be a slight mistake in the imaginary part (y).
    y = a.y*b.x - a.x*b.y / (b.x*b.x + b.y*b.y);
    But don't take my word for it. It's been ages since I did complex numbers -:)

  • Need help with a activation code for Adobe Acrobat X Standard for my PC,, Don't have older version serial numbers,  threw programs away,  only have Adobe Acrobat X Standard,  need a code to unlock program?

    Need help with a activation code for Adobe Acrobat X Standard for my PC, Don't have older Version of Adobe Acrobat 9, 8 or 7. 

    You don't need to install the older version, you only need the serial number from your original purchase. If you don't have them to hand, did you register? If so, they should be in your Adobe account. If not you really need to contact Adobe, though it isn't clear they will be able to do anything without some proof of purchase etc.

  • Need Help With File Matching Records

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

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

  • I need help with Creating Key Pairs

    Hello,
    I need help with Creating Key Pairs, I generate key pais with aba provider, but the keys generated are not base 64.
    the class is :
    import java.io.*;
    import java.math.BigInteger;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import au.net.aba.crypto.provider.ABAProvider;
    class CreateKeyPairs {
    private static KeyPair keyPair;
    private static KeyPairGenerator pairGenerator;
    private static PrivateKey privateKey;
    private static PublicKey publicKey;
    public static void main(String[] args) throws Exception {
    if (args.length != 2) {
    System.out.println("Usage: java CreateKeyParis public_key_file_name privete_key_file_name");
    return;
    createKeys();
    saveKey(args[0],publicKey);
    saveKey(args[1],privateKey);
    private static void createKeys() throws Exception {
    Security.addProvider(new ABAProvider());
    pairGenerator = KeyPairGenerator.getInstance("RSA","ABA");
    pairGenerator.initialize(1024, new SecureRandom());
    keyPair = pairGenerator.generateKeyPair();
    privateKey = keyPair.getPrivate();
    publicKey = keyPair.getPublic();
    private synchronized static void saveKey(String filename,PrivateKey key) throws Exception {
    ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(filename));
    out.writeObject(key);
    out.close();
    private synchronized static void saveKey(String filename,PublicKey key) throws Exception {
    ObjectOutputStream out= new ObjectOutputStream( new FileOutputStream(filename));
    out.writeObject(key);
    out.close();
    the public key is:
    �� sr com.sun.rsajca.JSA_RSAPublicKeyrC��� xr com.sun.rsajca.JS_PublicKey~5< ~��% L thePublicKeyt Lcom/sun/rsasign/p;xpsr com.sun.rsasign.anm����9�[ [ at [B[ bq ~ xr com.sun.rsasign.p��(!g�� L at Ljava/lang/String;[ bt [Ljava/lang/String;xr com.sun.rsasign.c�"dyU�|  xpt Javaur [Ljava.lang.String;��V��{G  xp   q ~ ur [B���T�  xp   ��ccR}o���[!#I����lo������
    ����^"`8�|���Z>������&
    d ����"B��
    ^5���a����jw9�����D���D�)�*3/h��7�|��I�d�$�4f�8_�|���yuq ~
    How i can generated the key pairs in base 64 or binary????
    Thanxs for help me
    Luis Navarro Nu�ez
    Santiago.
    Chile.
    South America.

    I don't use ABA but BouncyCastle
    this could help you :
    try
    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    java.security.KeyPairGenerator kg = java.security.KeyPairGenerator.getInstance("RSA","BC");
    java.security.KeyPair kp = kg.generateKeyPair();
    java.security.Key pub = kp.getPublic();
    java.security.Key pri = kp.getPrivate();
    System.out.println("pub: " + pub);
    System.out.println("pri: " + pri);
    byte[] pub_e = pub.getEncoded();
    byte[] pri_e = pri.getEncoded();
    java.io.PrintWriter o;
    java.io.DataInputStream i;
    java.io.File f;
    o = new java.io.PrintWriter(new java.io.FileOutputStream("d:/pub64"));
    o.println(new sun.misc.BASE64Encoder().encode(pub_e));
    o.close();
    o = new java.io.PrintWriter(new java.io.FileOutputStream("d:/pri64"));
    o.println(new sun.misc.BASE64Encoder().encode(pri_e));
    o.close();
    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader("d:/pub64"));
    StringBuffer keyBase64 = new StringBuffer();
    String line = br.readLine ();
    while(line != null)
    keyBase64.append (line);
    line = br.readLine ();
    byte [] pubBytes = new sun.misc.BASE64Decoder().decodeBuffer(keyBase64.toString ());
    br = new java.io.BufferedReader(new java.io.FileReader("d:/pri64"));
    keyBase64 = new StringBuffer();
    line = br.readLine ();
    while(line != null)
    keyBase64.append (line);
    line = br.readLine ();
    byte [] priBytes = new sun.misc.BASE64Decoder().decodeBuffer(keyBase64.toString ());
    java.security.KeyFactory kf = java.security.KeyFactory.getInstance("RSA","BC");
    java.security.Key pubKey = kf.generatePublic(new java.security.spec.X509EncodedKeySpec(pubBytes));
    System.out.println("pub: " + pubKey);
    java.security.Key priKey = kf.generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(priBytes));
    System.out.println("pri: " + priKey);
    catch(Exception e)
    e.printStackTrace ();
    }

Maybe you are looking for

  • Question on the result of using Wavelet transform on sine wave

    Dear all, I have apply the Wavelet transform on a 50Hz sine wave. The result is shown below. But I don't understand the result of Wavelet transform. Anyone can help me? Thanks. Victor

  • BEX Issue:Intgration of master data and Open Items cube data

    Hello Gurus, I need some help in BEX queries. I have master data Contract Objects which has master information like Max Number of payment and monthly installments. In the open items cube I had open items balance for multiple line items. So I need a r

  • Unplanned Delivery Costs and Price Variance - Account Determination

    Hi, I am facing the following issue: My goal is to automatic post the unplanned delivery costs to an account depending on valuation class. The account should be diferent from the one used in purchase (EIN)  post but both values should affect the movi

  • HTTP Query String

    We use mod_plsql to create webpages. One annoying charactersitic of this framework is having to explicitly define all Query String parameters that a procedure could possibly accept. We have some jquery stuff we're developing that retrieves data from

  • Modify or enhance in BP screen

    Hi gurus. My requirement is: In Tcode BP when communication type is set to email then set email field as madetory. Another if payment is by SMS then mobile field must be madetory. like wise few more fields to be mandetory. So for setting fields mandi