Need help with rotation in Java

Hi, I am trying to write an asteroids remake and I have gotten pretty far, but I'm stuck when I try to rotate my ship object. I have googled various formula's etc. but the code doesn't work as expected. I have posted the relevant ship.class below:
import java.awt.Polygon;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.*;
public class Ship extends MyShape {
     Polygon body;
     //line2D.Double base;
     //line2D.Double lside;
     //line2D.Double rside;
     double dx;
     double dy;
     double angle;
     double dAngle;
     Graphics2D gg;
     public Ship(double a,double b) {
    x=a;
    y=b;
    //base=new line2D.Double(x,y,x+10,y);
    //lside=new line2D.Double(x,y,x+5,y-10);
    //rside=new line2D.Double(x+10,y,x-5,y-10);
    body=new Polygon();
    body.addPoint((int)x,(int)y);
    body.addPoint((int)x+20,(int)y);
    body.addPoint((int)x+10,(int)y-30);
    public void advance(){
    public double getX(){
         return x;
    public double getY(){
         return y;
    public void setY(int y){
         this.y=y;
    public void setX(int x){
         this.x=x;
      public void move(int delta){
      body.translate(0,delta);
       // body.addPoint(x,y);
       // body.addPoint(x+20,y);
       // body.addPoint(x+10,y-30);
    public void rotate(double x, double y, double theta){
         //body=new Polygon();
         theta=theta*(Math.PI/180);
         x=((x-(x+10))*Math.cos(theta)-y*Math.sin(theta)+(x+10));
         y=(y*Math.cos(theta)+(x-(x+10))*Math.sin(theta)+y);
             //body.translate((int)Math.round(x),(int)Math.round(y));
             body.addPoint((int)Math.round(x),(int)Math.round(y));
             body.addPoint((int)Math.round(x+20),(int)Math.round(y));
             body.addPoint((int)Math.round(x+10),(int)Math.round(y-30));
             //g.rotate(theta,x,y);
    public void warpAround(int x,int y){
         body.translate(x,y);
    public void draw(Graphics2D g){
         g.draw(body);
}If you could help me I would appreciate it,
Sincerely,
LJ
P.s. I know its a little rough, I wanted to clean it up soon.
Message was edited by:
nipponman21

Ok, I have officially given up on trying to get it to work via the mathematical definitions of a rotational transform. I decided to use the affine transform and it was MUCH easier than I thought to implement; however, the results are still unexpected, the ship actually turns and moves in a circle which is not what I want, here is the source (its a standalone app so you can compile and run it if you want) import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class BouncingBall extends JFrame implements Runnable, KeyListener {
    //Windows
    private JFrame frame;
    private DrawPanel pane; 
    private Thread t;
    //Game Vars.
    public Ball ball;
    public Ship ship;
    public static final int FPS = 30;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    public static final int MAXSPEED = 30;
    public static double dx,dy;
    public static int theta=0;
    public BouncingBall() {
         frame=new JFrame();
         pane=new DrawPanel();
         frame.getContentPane().add(pane);
         frame.setVisible(true);
         frame.pack();
         frame.addKeyListener(this);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         initGame();
         start();
    public void initGame(){
         ship=new Ship();
         ball=new Ball();
    public void start(){
    t=new Thread(this);
         t.start();
        public void run(){
             while(true){
                  try{
                  Thread.sleep(10);
                  }catch(Exception e){}
                  pane.repaint();
    public static void main(String[] args) {
        new BouncingBall();
    public void keyPressed(KeyEvent e){
        switch(e.getKeyCode()){
               case KeyEvent.VK_UP:
               dy--;
               if(dy<MAXSPEED){
               ship.move(0,dy);
               else{
               dy=MAXSPEED;
               ship.move(0,dy);
               break;
               case KeyEvent.VK_LEFT:
                    theta++;
                    break;
               case KeyEvent.VK_RIGHT:
                    theta--;
                    break;     
    repaint();
    public void keyReleased(KeyEvent e){
        switch(e.getKeyCode()){
               case KeyEvent.VK_UP:
               case KeyEvent.VK_DOWN:
               dy=0;     
               break;
    repaint();
    public void keyTyped(KeyEvent e){
    class Ball{
          double x;
          double y;
         private Arc2D.Double body;
         public Ball(){
              x=600.0;
              y=500.0;
              body=new Arc2D.Double(x,y,30.0,30.0,0.0,360.0,Arc2D.OPEN);
         public void move(double dx,double dy){
              body=new Arc2D.Double();
              x+=dx;
              y+=dy;
              body=new Arc2D.Double(x,y,30.0,30.0,0.0,360.0,Arc2D.OPEN);
         public double getX(){
         return this.x;
         public double getY(){
         return this.y;
    class Ship{
          double x;
          double y;
          double angle;         
         private Polygon body;
         public Ship(){
              x=400.0;
              y=300.0;
              angle=0;
              body=new Polygon();
              body.addPoint((int)Math.round(x),(int)Math.round(y));
              body.addPoint((int)Math.round(x+15),(int)Math.round(y));
              body.addPoint((int)Math.round(x+7.5),(int)Math.round(y-20));
         public void move(double dx,double dy){
              body=new Polygon();
              x+=dx;
              y+=dy;
              body.addPoint((int)Math.round(x),(int)Math.round(y));
              body.addPoint((int)Math.round(x+15),(int)Math.round(y));
              body.addPoint((int)Math.round(x+7.5),(int)Math.round(y-20));
         public double getX(){
         return this.x;
         public double getY(){
         return this.y;
    class DrawPanel extends JPanel{
            public DrawPanel(){
              setBackground(Color.black);
              setPreferredSize(new Dimension(BouncingBall.WIDTH,BouncingBall.HEIGHT));
         public void paintComponent(Graphics g){
             super.paintComponent(g);
             Graphics2D g2d=(Graphics2D)g;
             g2d.setColor(Color.white);
             g2d.fill(ball.body);
             g2d.rotate(theta*Math.PI / 180.0);     
             g2d.fill(ship.body);
}Can you guys maybe run this and look over the code and tell me what I'm doing wrong? I would definitely appreciate it Thanks.

Similar Messages

  • Im DROWNING! need help with a simple java assignment! plz someone help me!

    i need help with my java assignment, with validating a sin number. easy for must who know java. im drowning... please help!

    You will need to store each digit of the social insurance number in a field of its own. To validate the entry you will:
    1. Multiply the 2nd, 4th, 6th and 8th digit by 2.
    2. If the product of any of the four multiplications result in a value greater than 9, add the two resulting digits together to yield a single-digit response. For example 6 * 2 = 12, so you would add the 1 and the 2 to get a result of 3.
    3. Add these four calculated values together, along with the 1st, 3rd, 5th, and 7th digits of the original number.
    4. Subtract this sum from the next highest multiple of 10.
    5. The difference should be equal to the 9th digit, which is considered the check digit.
    Example of validating S.I.N. 765932546
    1st digit 7
    2nd digit (6*2 =12 1+2=) 3
    3rd digit 5
    4th digit (9*2 = 18 1+8 =) 9
    5th digit 3
    6th digit (2*2 = 4) 4
    7th digit 5
    8th digit (4*2 = 8) 8
    Total 44 next multiple of 10 is 50
    50-44 = 6 which is the 9th digit
    Therefore the S.I.N. 765932546 is Valid
    ********* SIN Validation *********
    Welcome - Please enter the first number: 120406780
    Second digit value multiplied by 2 4
    Fourth digit value multiplied by 2 8
    Sixth digit value multiplied by 2 12
    Eighth digit value multiplied by 2 16
    Value derived from 6th digit 3
    Value derived from 8th digit 7
    The total is 30
    Calculated digit is 10
    Check digit must be zero because calculated value is 10
    The SIN 120406780 is Valid
    this is my assignemtn this is what i have! i dont know where to start! please help me!
    /*     File:     sinnumber.java
         Author:     Ashley
         Date:     October 2006
         Purpose: Lab1
    import java.util.Scanner;
    public class Lab1
              public static void main(String[] args)
                   Scanner input = new Scanner(System.in);
                   int sin = 0;
                   int number0, number1, number2, number3, number4, number5, number6, number7, number8;
                   int count = 0;
                   int second, fourth, sixth, eighth;
                   System.out.print("\t\n**********************************");
                   System.out.print("\t\n**********SIN Validation**********");
                   System.out.print("\t\n**********************************");
                   System.out.println("\t\nPlease enter the First sin number: ");
                   sin = input.nextInt();
                   count = int.length(sin);     
                   if (count > 8 || count < 8)
                   System.out.print("Valid: ");
         }

  • Need help with mac and java

    Hi, I'm trying to develop an application on a Machintosh OSX 10.2.8 machine.
    I'm having a herrendous time trying to get quicktime to work on it.
    I've somehow managed t oget 1.3.1 and QTJava.jar to work together but now i need encryption, however that requires 1.4+
    Now 1.4.1 doesnt work with quicktime
    I've downloaded the latest software upgrades but Ive got no idea how to set up quicktime to work with java 1.4.1
    Now to add on top of that mac reports it can use AES encryption. this is from source code ripped striaght from this website.
    But first and foremost can anyone, annyonee help me out with setting up 1.4.1 with quicktime?
    Thank you

    If you need encryption with Java 1.3.1, download the JCE from either Sun (http://java.sun.com/products/jce/) or Bouncy Castle (http://www.bouncycastle.org/).
    Cheers,
    --Arnout                                                                                                                                                                                                                                                                                                                                                                   

  • Need help with long term Java problems

    I've been having problems with Java on my computer for about a year now, and I'm hoping that someone here can help me out.
    Java used to work fine on the computer when I first got it (a Dell laptop) and I hadn't installed anything myself. But then one day it stopped loading Java applets, and hasn't worked since. By this, I mean that I get the little colorful symbol in a box when I try to play Yahoo games, use the http://www.jigzone.com site, go to chat rooms, etc. Java menus on websites like http://www.hartattack.tv used to work still, but lately they've been giving me that symbol too.
    I've tried downloading a newer version of Java, but nothing I do seems to work, and I don't know of anything I did to trigger it not working. I'm hoping there's a simple solution to this, and I'm just dumb.
    Thanks.

    This might be way off, but it's something that's tripped me up in the past:
    If you are using Sun's Java plugin, the first time you go to a site that has a particular Java applet, you may be asked to approve/reject a security request.
    If you have clicked on any other windows while the request is first being loaded (which can take some time, because this is swing based), then the security dialog box does not pop to the top of the window stack, and doesn't add an entry into the task bar.
    It appears that Java just doesn't work, but it's actually waiting for you to click "Yes". You can check this by hitting alt-tab and seeing if the Java coffee cup icon is one of the options.
    - K

  • Need Help with Rotating Banner ad(please help)

    I am currently working on a flash project that rotates banners out auto and with button control, got the buttons to work just cant figure out how to get it  auto play throgh my bannersThis is the code i have for my project I am working on:
    My Projects has 3 layers:
    ( layer3)Actions:(coded on first frame)     Movieclip.prototype.elasticMove =  function(target, accel, convert) {
         step = step * accel + (target - this._x) * convert;
         this._x += step;
    (layer 2) My movie clip(it is one long strip that has all the banners in a row)(coded on first frame):nClipEvent  (enterFrame) {
                                         elasticMove(_root.newX, 0.5, 0.3)
    onClipEvent(load){
    _root.newX= 1200;
    (layer1)(my buttons)(only code for one button all are the same code except the actual position they call):on(release){
    _root.newX=1200;
    Let me know if i need to be a little more clear or you want a snap shot of my work, Another individual suggested that I use this code in the action layer:
    var newXA:Array=[0,600,1200,1800];
    var index:Number=1;
    setInterval(newXF,9000);
    function newXF(){
    _root.newX = newXA[index%newXA.length];
    It seems to work in the sense after a little bit it does change the banner auto and after you stayed on a banner for a while, but it always changes to the same banner.
    PLEASE HELP SOMEONE!!!!!!

    Incognito mode is a Google Chrome setting when you open a new window (Cmd+Shift+N on a Mac Ctrl+Shift+N on Windows) It opens a "private" window with no cookies and no tracking. The problem with it is that when you disable cookies, your license files are not sent to the site (whetehr it's YouTube or xFinity or any other that uses license files for paid content)  and it treats you as if you're a first time visitor. Paid videos won't play wihtout the cookies sending the license file info.
    This isn't a Flash Player setting. It's in Chrome. I did some research and according to Google, "Incignito" mode is off by default, and can ONLY be activate by the keyboard shortcut. There IS a way to disable it from the registry http://dev.chromium.org/administrators/policy-list-3#IncognitoModeAvailability

  • Need help with running a Java program on Linux

    I am trying to get a Java program to run on a Linux machine. The program is actually meant for a Mac computer. I want to see if someone with Java experience can help me determine what is causing the program to stall. I was successful in getting it installed on my Linux machine and to partially run.
    The program is an interface to a database. I get the login screen to appear, but then once I enter my information and hit enter the rest of the program never shows, however, it does appear to connect in the background.
    Here is the error when I launch the .jar file from the command screen:
    Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    I am not a programmer and I am hoping this will make some sense to someone. Any help in resolving this is greatly appreciated!

    Well, without knowing a little bit about programming, and how to run your debugger, I don't think you're going to fix it. The IllegalArgumentException is saying that some call does not like what it's getting. So you'll have to go in an refactor at least that part of the code.

  • Need help with settng up JAVA environment

    Hi:
    Can someone help me?
    How do you set up PATH and CLASSPATH?
    I downloaded the J2SDK VERSION 1.4. Then installation created the java folder j2sdk. So now all the files are in C:\J2SDK\such as lib,bin,read me right! What do I do next?
    Now how do I set my environment variables.Plus I created a new folder called Khava on my desktop to put my source code files.
    Appreciate any help
    Thanks.

    depends on ur OS. If you are running Windows 9X/2K/Me...find your autoexec.bat file. Either right-click and edit it or type "edit autoexec.bat" in DOS. In there, add to your current PATH line (or create one if you don't) that has the bin folder in it.
    So in your case, append this to the PATH= line:
    C:\J2SKD\bin
    should be all you need.
    Save and either restart the puter or run autoexec.bat. To check to see if it worked, type "PATH" in DOS and it'll display ur current path. Hope this helps.

  • Need help with a basic java thing..

    Sorry, just started java a few weeks ago and i'm having trouble figuring out how to do something.
    I wanted to know how to make this work. It cant be more than 6 characters in length and of those six characters, the first two have to be letters only, followed by a dash (-) and then three numbers. EG: ab-234 or gf-643...
    Im using it as a serial number generator type thing, thats only one part of the entire program, but I cant figure it out.
    Just need the most basic way to do that if anyone could help! been looking for hours in a couple java books i have and dont know where to look or what to look for!!
    Any help figuring out the code for that would be great! Here's what I have so far and how i need the rest to be implemented! Thanks! PS: using TextIO
    <code>
    String itemNum1
         itemNum1 = new String ( " Enter Item Number(AB-123): " );
         TextIO.put("\n" + itemNum1);
         itemnum = TextIO.getlnString();
    </code>

    Oh hey sorry, i figured the bit of text i put in there
    would be enough. I basically need a user to enter the
    information, but i just need to know (or get a hint)
    of how to prevent them from entering an invalid
    number/serial code type thing in regards to the
    parameters that I need met. (such as no more than 6
    chars, but alternating numbers/letters). I presume I
    use the char and not the getlnString command but
    nonetheless im still stuck as to how I'd manage that.
    Do i need to code each character seperately? (such as
    letters by themselves, then another prompt to enter
    the numbers??) or is there a way to get it all in one
    go?
    Thanks for any advice! oh and Sorry for the bad
    wording in my question :P.
    You could read the String from console using something like
    public static String readWord()
       {  int ch;
          String r = "";
          boolean done = false;
          while (!done)
          {  try
             {  ch = System.in.read();
                if (ch < 0
                   || java.lang.Character.isSpace((char)ch))
                   done = true;
                else
                   r = r + (char) ch;
             catch(java.io.IOException e)
             {  done = true;
          return r;
       }you would have to modify it according to your needs and after that you could use the String API to confirm if the user has entered it right or not. If not you could ask him to do that again

  • I need help with rotation interpolators

    I draw a big sphere which represents the earth and distribute on this big sphere small spheres represent countries.
    Now I want draw cone move between 2 small sphere.
    I have used rotation path interpolator but the motion of the cone not appear to me since the cone motion is within the big sphere.
    I want the cone start from first small sphere then turn around big sphere ti go to second small sphere.
    could you help me please?
    this is the code I used to make the motion
    float[] knots = {0.0f, 1.0f};
            Quat4f[] quats = new Quat4f[2];
            Point3f[] positions = new Point3f[2];
            positions[0] = flowNodes.get(sourceNode);
            positions[1] = flowNodes.get(destNode);
            // some checks for source and destination positions to set the right angel for the motion
            if(positions[0].x < positions[1].x&& positions[0].y < positions[1].y)
                 quats[0] = new Quat4f(1.0f,0.0f, 1.0f, (float)(-rotationAngel+Math.toRadians(45)));
                 quats[1] =  new Quat4f(1.0f,0.0f, 1.0f,(float)(-rotationAngel+Math.toRadians(45)));
            else if(positions[0].x==positions[1].x&&positions[0].y<positions[1].y)
                quats[0] = new Quat4f(1.0f,1.0f, 0.0f, (float)(-Math.toRadians(180)));
                quats[1] =  new Quat4f(1.0f,1.0f, 0.0f,(float)(-Math.toRadians(180)));
            else if(positions[0].x < positions[1].x&& positions[0].y > positions[1].y)
                quats[0] = new Quat4f(1.0f,0.0f, 1.0f, (float)(rotationAngel+Math.toRadians(10)));
                quats[1] =  new Quat4f(1.0f,0.0f, 1.0f,(float)(rotationAngel+Math.toRadians(10)));
            else if(positions[0].x == positions[1].x&& positions[0].y == positions[1].y)
                quats[0] = new Quat4f(1.0f,0.0f, 1.0f, (float)(rotationAngel+Math.toRadians(45)));
                quats[1] =  new Quat4f(1.0f,0.0f, 1.0f,(float)(rotationAngel+Math.toRadians(45)));
            else
                quats[0] = new Quat4f(1.0f,0.0f, 1.0f, (float)(rotationAngel));
                quats[1] = new Quat4f(1.0f,0.0f, 1.0f,(float)(rotationAngel));
    *creating the interpolator and give for this interpolator the highest priority to begin*
    motion now and then adding the interpolator to the branch group
            RotPosPathInterpolator rotPosPath = new RotPosPathInterpolator(alpha, arrowTG, arrowT3D, knots, quats, positions);
            rotPosPath.setSchedulingBounds(new BoundingSphere());
            rotPosPath.setSchedulingInterval(0);
            arrowGroup.addChild(rotPosPath); Edited by: walaa_akram on Jun 4, 2009 3:25 PM

    Please read through the help files. The w key activates rotation which will give you slightly different tools if the layer is 2D or 3D. The v key will give you the selection key. You should be able to click any tool in the tool bar. If you want to manually enter values press the r key with a layer selected in the time line to bring up rotation properties.
    I promise you that you cannot learn how to use After Effects efficiently without going through some training. I've been teaching AE for a little more than 20 years and I've never seen a single person successfully stumble through the app and produce anything other than a direct copy of someone else's project. Start here: Basic Workflow

  • Computer idiot needs help with  vista and java

    -running vista home edition 64bit
    - i am administrator
    -need to run an older version of java jdk/jre6 update 6
    - when i download the appropriate version for the windows 64 bit, I go through the installation and finish it but java never appears in my control panel
    - if i download the version for just windows the java icon appears in my control panel but IE7 does not recognize it as being there
    HELP

    AFTER I break down and erase the HD and reinstall OSX
    You don't have to erase the drive to reinstall the OS. Just reinstall WITHOUT erasing the drive. Only system files will be over-written, and your borked OS will be fixed, while your own files will be left in place. You really should have a backup before a reinstall, but unless one is very unlucky and something goes wrong it isn't strictly necessary.
    Never trash anything unless you know what it is, what it does, why it is doing it, and what put it there to do that. I know, it's a bit late for this crisis, but you should now avoid future crises caused by throwing away (or moving) the wrong thing.
    Francine
    Francine
    Schwieder

  • Need help with porting from Java 1.1 to 1.4

    One of our applications is an applet and we're in the
    process of upgrading it's version of Java from 1.1 to 1.4. For the most part,the upgrade has gone smoothly, but we are having two big problems. The first problem is that the list objects on one of the windows resize when a mouse event occurs on the Tabbed Panel it sits on. The list object is made from a Symantec class called MultiList. The list actually shrinks so that the data on it can hardly be seen.
    The other problem is that when dispose() is called on all of the windows, an IllegalStateException: Cannot dispose InputContext while its active error occurs.

    If you people have nothing good to say, please do the
    rest of us in the forum(s) a favor and don't say
    anything at all.
    Also, do not assume that threads are posted because
    people are lazy and haven't researched their
    problem(s).
    People post threads in these forums looking for help,
    not abuse.What are you talking about?
    If the original poster disregarded my advice and searched the bug database as indicated, they would have found the answer to their question. I know. I had the same problem and solved it by using the workaround I found in the bug database.
    I would say it was very helpful advice.

  • I need help with looping a java file

    I am wondering is it possable to loop a java file. By this i mean re-run it again from a particular point in the program. Like where i have marked out below.
    import java.util.*;
    public class Player
    public static void main(String[] args){
    Songs listing = new Songs();
    Player gui = new Player();
    listing.readarray();
    // I would like to loop it here once the option has been selected.
    Scanner myScanner = new Scanner(System.in);
    int option1;
    System.out.println("--------Options-------");
    System.out.println(" ");
    System.out.println("Type Option Number ");
    System.out.println(" ");
    System.out.println("1 :View Songs");
    System.out.println("2 :View Playlist");
    System.out.println("3 :Edit Playlist");
    System.out.println("4 :Play Playlist");
    System.out.println(" ");
    System.out.println("What option would you like?");
    option1 = myScanner.nextInt();
    if (option1 == 1)
    listing.disparray();

    import java.util.*;
    public class Player
    public static void main(String[] args){
    Songs listing = new Songs();
    Player gui = new Player();
    listing.readarray();
    *while (true)*
    // I would like to loop it here once the option has been selected.
    Scanner myScanner = new Scanner(System.in);
    int option1;
    System.out.println("--------Options-------");
    System.out.println(" ");
    System.out.println("Type Option Number ");
    System.out.println(" ");
    System.out.println("1 :View Songs");
    System.out.println("2 :View Playlist");
    System.out.println("3 :Edit Playlist");
    System.out.println("4 :Play Playlist");
    System.out.println(" ");
    System.out.println("What option would you like?");
    option1 = myScanner.nextInt();
    if (option1 == 1)
    listing.disparray();
    }}

  • I need help with setting up my Sun Java Studio Creator

    Hello all, i need help with setting up the Studio Creator, i"m new to all that staff so is there anyone to help me just a little with all that if yes email me at [email protected] or get me on AOL Instant Messanger with the screen name: wretch17
    thanks :-)

    Hi,
    Welcome to the Creator community! Thanks for your interst in Sun Java Studio Creator. Please feel free to post any question related to creator on this forum .
    Take a look the creator website at
    http://developers.sun.com/prodtech/javatools/jscreator/
    CreatorTeam

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • 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.

Maybe you are looking for