organization - How can I organize my Java code? -


the title not entire question. know how organize code, theoretically, specific, useful, pointers. please read on before griping.

i'm beginner java , oop (object oriented programming) , learn how better organize code! on course of month or two, made calculator program little functions thought of here , there few small jokes built it. after looking @ second time realized extremely poorly formatted , incomprehensible.if may, ask more experienced programmers point me in right direction on should fix (for example, things can turn objects, can compartmentalize, etc).

please note first time posting on forum if need clarify me, i've done wrong, i'm asking much, please tell me can resolve , can help. please dont mark invalid , file away oblivion (as happens in stackoverflow). also, before asks, no not homework, product of own crack @ teaching myself java (probably why not working well).

here source code:

// original calculator code without objects in single class. not efficient... package randomclasses; import java.awt.*; import java.awt.event.*; import java.text.decimalformat; import javax.swing.*;  @suppresswarnings("serial") public class calcclass         extends jframe         implements actionlistener {     jpanel[] row = new jpanel[6];     jbutton[] button = new jbutton[21];     string[] buttonstring = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "/", "c", "v", "+/-", "=", "0", "parabola", "x^y"};     int[] dimw = {300, 45, 100, 90, 180};     int[] dimh = {35, 40};     dimension displaydimension = new dimension(dimw[0], dimh[0]);     dimension regulardimension = new dimension(dimw[1], dimh[1]);     dimension rcolumndimension = new dimension(dimw[2], dimh[1]);     dimension zerobutdimension = new dimension(dimw[3], dimh[1]);     dimension paraboladimension = new dimension(dimw[4], dimh[0]);     //formatting variables     int var = 0;     double x = 0;     string stor = "";     boolean initial = true;     //variables parabola function     int countequals_parab = 0;     double angle = 0;     double vi = 0;     double vx = 0;     double vy = 0;     double t_max = 0;     double y_displ = 0;     double x_displ = 0;     double h = 0;     double k = 0;     double a_parab = 0;     boolean parabcomplete = true;     boolean parabola = false;     decimalformat df = new decimalformat("#######.#####");     //variables addressing illegal typing issues     boolean typenum = true;     boolean typedot = true;     jframe frame; //for parabolainstructions     //original calculator variables     boolean[] function = new boolean[5];     double[] temporary = {0, 0}; //store on screen values     double result = 0; //store result     public jtextarea display = new jtextarea(1, 20);     font font = new font("times new roman", font.bold, 14);      calcclass() {         super("calcclass");         setdesign();         setsize(380, 300);         setresizable(false);         setdefaultcloseoperation(exit_on_close);         gridlayout grid = new gridlayout(6, 5);         setlayout(grid);         for(int = 0; < 5; i++) {             function[i] = false;         }         flowlayout f1 = new flowlayout(flowlayout.center);         flowlayout f2 = new flowlayout(flowlayout.center, 1, 1);         for(int = 0; < 6; i++) {             row[i] = new jpanel();         }         row[0].setlayout(f1);         for(int = 1; < 6; i++) {             row[i].setlayout(f2);         }         for(int = 0; < 21; i++) {             button[i] = new jbutton();             button[i].settext(buttonstring[i]);             button[i].setfont(font);             button[i].addactionlistener(this);         }         display.setfont(font);         display.seteditable(false);         display.setpreferredsize(displaydimension);         for(int = 0; < 14; i++) {             button[i].setpreferredsize(regulardimension);         }         for(int = 14; < 18; i++) {             button[i].setpreferredsize(rcolumndimension);         }         button[18].setpreferredsize(zerobutdimension);         button[19].setpreferredsize(paraboladimension);         button[20].setpreferredsize(rcolumndimension);         row[0].add(display);         add(row[0]);         for(int = 0; < 4; i++) {             row[1].add(button[i]);         }         row[1].add(button[14]);         add(row[1]);         for(int = 4; < 8; i++) {             row[2].add(button[i]);         }         row[2].add(button[15]);         add(row[2]);         for(int = 8; < 12; i++) {             row[3].add(button[i]);         }         row[3].add(button[16]);         add(row[3]);         row[4].add(button[18]);         for(int = 12; < 14; i++) {             row[4].add(button[i]);         }         row[4].add(button[17]);         add(row[4]);         row[5].add(button[19]);         row[5].add(button[20]);         add(row[5]);         setvisible(true);     }      public void getsqrt() {         stor = "";         initial = true;         try {             double value = double.parsedouble(display.gettext());             if(value == -100) {                 format("john's girlfriend");             } else {                 value = math.sqrt(double.parsedouble(display.gettext())); //create value variable, , use maths square root find value                 format(double.tostring(value)); //sets display new value             }         } catch(numberformatexception e) {         }         typedot = false;         typenum = false;     }      public void getposneg() {         stor = "";         initial = true;         try {             double value = double.parsedouble(display.gettext()); //again creating variable current value             if(value != 0) { //if value not equal 0                 value = (-1) * value; //multiplied -1 change sign                 format(double.tostring(value)); //sets display new value             } else {             }         } catch(numberformatexception e) {         }     }      public void getresult() {         temporary[1] = double.parsedouble(display.gettext());         string temp0 = double.tostring(temporary[0]);         string temp1 = double.tostring(temporary[1]);         try {             if(temp0.contains("-")) {                 string[] temp00 = temp0.split("-", 2);                 temporary[0] = (double.parsedouble(temp00[1]) * -1);             }             if(temp1.contains("-")) {                 string[] temp11 = temp1.split("-", 2);                 temporary[1] = (double.parsedouble(temp11[1]) * -1);             }         } catch(arrayindexoutofboundsexception e) {         }         try {             functions();             clear();             format(double.tostring(result));//display has result             for(int = 0; < 5; i++) {                 function[i] = false; //set functions false             }         } catch(numberformatexception e) {         }         typenum = false;     }      public void functions() {         if(function[2] == true) { //multiplication              result = temporary[0] * temporary[1];         } else if(function[3] == true) { //division             result = temporary[0] / temporary[1];         } else if(function[0] == true) { //addition             result = temporary[0] + temporary[1];         } else if(function[1] == true) { //subtraction;             result = temporary[0] - temporary[1];         } else if(function[4] == true) {             result = math.pow(temporary[0], temporary[1]);         } else {             result = temporary[1];         }     }      double a_quadratic = 0;     double b = 0;     double c = 0;     double x1 = 0;     double x2 = 0;     double discr = 0;     int countequals_quadratic = 0;      public void quadraticformula() {         if(countequals_parab == 0) {             a_quadratic = double.parsedouble(display.gettext());             clear();             display.settext("b = ");         }         if(countequals_parab == 1) {             b = double.parsedouble(display.gettext());             display.settext("c = ");         }         if(countequals_parab == 2) {             c = double.parsedouble(display.gettext());             discr = (math.pow(b, 2) - 4 * a_quadratic * c); //stores value of discriminant             if(discr >= 0) {                 x1 = (-b + math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);                 x2 = (-b - math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);             }         }     }      public void parabolabutton() {         double g = 9.81;         if(countequals_parab == 0) {             vi = double.parsedouble(display.gettext());             clear();             display.settext("angle of release: ");         }         if(countequals_parab == 1) {             angle = double.parsedouble(display.gettext());             if((angle > 90.0) || (angle < 0.0)) {                 display.settext("sorry, not valid angle");                 countequals_parab = 3;             } else {                 angle = (math.pi / 180.0) * angle;  //converting degrees radians                 vx = vi * math.cos(angle); //calculating x component                 vy = vi * math.sin(angle); //calculating y component                 //finding time                 t_max = vy / g; //time max height                 //calculating vertex coordinates                 y_displ = (vy * vy / (2 * g));                 x_displ = vx * t_max;                 //finding                 a_parab = (-y_displ) / (x_displ * x_displ);                 display.settext("the equation of parabola \ny = " + df.format(a_parab) + "(x - " + df                         .format(h) + ")^2 + " + df.format(k));             }         }         if(countequals_parab == 2) {             display.settext("time max height = " + df.format(t_max));         }         if(countequals_parab == 3) {             clearfunction();             countequals_parab = -1;             parabola = false;             parabcomplete = true;         }         countequals_parab++;     }      public void var() {         var++;         if(var > 8) {             var = 1;         }         if(var == 1) {             format("x");         }     }      public final void setdesign() {         try {             uimanager.setlookandfeel("com.sun.java.swing.plaf.nimbus.nimbuslookandfeel");         } catch(exception e) {         }     }      public void format(string get) {         //get stores incoming values temporarily         //get transferred new value permanent storage         //print permanent storage value         //new number added, stored temporarily in         //get added permanent storage         //print permanent storage value         double spacefix = 0;         if(initial == true) {             stor = get;             initial = false;         } else if(initial == false) {             stor = stor + get;         }         spacefix = stor.length() / 4;         int numberofspaces = 56 - stor.length() + (int) spacefix;         string format = string.format("%" + numberofspaces + "s", stor);         display.settext(format);     }      @override     public void actionperformed(actionevent ae) {         if(ae.getsource() == button[0]) {             numberbuttons("7");         }         if(ae.getsource() == button[1]) {             numberbuttons("8");         }         if(ae.getsource() == button[2]) {             numberbuttons("9");         }         if(ae.getsource() == button[3]) {             operatorbuttons(0); //add function[0]         }         if(ae.getsource() == button[4]) {             numberbuttons("4");         }         if(ae.getsource() == button[5]) {             numberbuttons("5");         }         if(ae.getsource() == button[6]) {             numberbuttons("6");         }         if(ae.getsource() == button[7]) {             operatorbuttons(1); //subtract function[1]         }         if(ae.getsource() == button[8]) {             numberbuttons("1");         }         if(ae.getsource() == button[9]) {             numberbuttons("2");         }         if(ae.getsource() == button[10]) {             numberbuttons("3");         }         if(ae.getsource() == button[11]) {             operatorbuttons(2); //multiplication function[2]         }         if(ae.getsource() == button[12]) {             if(typedot == false) {             } else {                 numberbuttons(".");                 typedot = false;             }         }         if(ae.getsource() == button[13]) {             operatorbuttons(3); //divide function[3]         }         if(ae.getsource() == button[14]) {             clearfunction();             parabola = false;             parabcomplete = true;         }         if(ae.getsource() == button[15]) {             getsqrt();         }         if(ae.getsource() == button[16]) {             getposneg();         }         if((ae.getsource() == button[17]) && display.gettext().equals("")) {         } else if((ae.getsource() == button[17]) && (parabola == false)) {             getresult();         } else if((ae.getsource() == button[17]) && (parabola == true)) {             parabolabutton();         }         if(ae.getsource() == button[18]) {             numberbuttons("0");         }         if(ae.getsource() == button[19]) {             clearfunction();             parabolainstructions();             parabola = true;             parabcomplete = false;             display.settext("initial velocity: ");         }         if(ae.getsource() == button[20]) {             operatorbuttons(4);//powerfunction();         }     }      public void parabolainstructions() {         //create dialog.         final jdialog dialog = new jdialog(frame, "how use parabola function");         //add contents it. must have close button,         //since l&fs (notably java/metal) don't provide 1         //in window decorations dialogs.         jlabel label = new jlabel("<html><p align=center>" + "step 1:  type in initial velocity , press \"=\" button<br>" + "step 2:  type in angle of release (make sure between 0 , 90)<br>" + "step 3:  press \"=\" button scroll through results<br>" + "step 4:  profit");         label.sethorizontalalignment(jlabel.center);         font font = label.getfont();         label.setfont(label.getfont().derivefont(font.plain, 14.0f));         jbutton closebutton = new jbutton("ok");         closebutton.addactionlistener(new actionlistener() {             public void actionperformed(actionevent e) {                 dialog.setvisible(false);                 dialog.dispose();             }         });         jpanel closepanel = new jpanel();         closepanel.setlayout(new boxlayout(closepanel, boxlayout.line_axis));         closepanel.add(box.createhorizontalglue());         closepanel.add(closebutton);         closepanel.setborder(borderfactory.                 createemptyborder(0, 0, 5, 5));         jpanel contentpane = new jpanel(new borderlayout());         contentpane.add(label, borderlayout.center);         contentpane.add(closepanel, borderlayout.page_end);         contentpane.setopaque(true);         dialog.setcontentpane(contentpane);         //show it.         dialog.setsize(new dimension(400, 200));         dialog.setlocationrelativeto(frame);         dialog.setvisible(true);     }      public void numberbuttons(string i) {         if(typenum == false) {             display.settext("");             format(i);         } else {             format(i);         }         typenum = true;     }      public void operatorbuttons(int funct) {         if(display.gettext().equals("")) {         } else {             temporary[0] = double.parsedouble(display.gettext());             function[funct] = true;             clear();         }     }      public void clearfunction() {         clear();         try {             for(int = 0; < 5; i++) {                 function[i] = false;             }             for(int = 0; < 2; i++) {                 temporary[i] = 0;             }         } catch(nullpointerexception e) {         }         //for parabola()         vi = 0;         vx = 0;         vy = 0;         t_max = 0;         y_displ = 0;         x_displ = 0;         h = 0;         k = 0;         a_parab = 0;     }      public void clear() {         display.settext("");         stor = "";         typedot = true;         initial = true;     }      public static void main(string[] arguments) {         calcclass c = new calcclass();     } } 

ok you've seen mess... sort-of know should , yes did research feel easier learn organization through example or nice push reading articles tell ultra-hypothetical or loosely-analogous examples of objects are. note: tried using methods organize , class looks better did (i made whole thing object called upon @ bottom pretty useless).

if use eclipse, try:

window > prefferences > java > editor > save actions

check "perform selected actions on save", "additional actions" , click "configure".

using eclipse's save actions can useful in real life coding, learn neat java tricks going through save actions wizard.

java object oriented language. need take advantage of fact.
use classes separate code different logical / structural components. learn how use oop. follow solid design , use design patterns.

another important thing know language. start reading basic classes javadocs , relevant sections of java spec. begin understanding different types of java (class, interface, enum , inner / nested / anonymous types) , different modifiers (private, public, protected, static, abstract, final, default).

some other eclipse's short cuts:

  • ctrl-a, ctrl-i ("indentation") fix code indentation.
  • ctrl-shift-o ("organize imports") omit redundant imports.


  • Comments

    Popular posts from this blog

    angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

    php - CakePHP HttpSockets send array of paramms -

    node.js - Using Node without global install -