HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Shortening calculator project code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codeprojectcalculatorshortening

Problem

I was told to create a calculator design on AWT, which is also my first project on AWT. I wrote the program and submitted it. I was then told that my program contains around 70 lines of code, and I should try to write less code. How can I shorten this code?

```
import java.awt.*;
class Demo{
Frame f;
TextField tf;
Button add,sub,mul,div,find,zero,num1,num2,num3,num4,num5,num6,num7,num8,num9;
Button num0,decimal,per;
Demo(String s)
{
f=new Frame(s);
tf=new TextField("0");
tf.setBounds(20, 40, 205, 40);
f.add(tf);
add=new Button("+");
sub=new Button("-");
div=new Button("/");
mul=new Button("x");
find=new Button("=");
zero=new Button("C");
num1=new Button("1");
num2=new Button("2");
num3=new Button("3");
num4=new Button("4");
num5=new Button("5");
num6=new Button("6");
num7=new Button("7");
num8=new Button("8");
num9=new Button("9");
num0=new Button("0");
per=new Button("%");
decimal=new Button(".");
mul.setBounds(125,100,50,40);
add.setBounds(70,100,50,40);
sub.setBounds(15, 100, 50, 40);
div.setBounds(180, 100, 50, 40);
find.setBounds(180,250,50,88);
zero.setBounds(180, 150, 50, 40);
num9.setBounds(15,150,50,40);
num8.setBounds(70,150,50,40);
num7.setBounds(125,150,50,40);
num6.setBounds(15,200,50,40);
num5.setBounds(70,200,50,40);
num4.setBounds(125,200,50,40);
num3.setBounds(15,250,50,40);
num2.setBounds(70,250,50,40);
num1.setBounds(125,250,50,40);
num0.setBounds(15,300,105,40);
decimal.setBounds(125,300,50,40);
per.setBounds(180,200,50,40);
f.add(per);
f.add(add);
f.add(mul);
f.add(div);
f.add(sub);
f.add(find);
f.add(zero);
f.add(num1);
f.add(num2);

Solution

Write a helper method, e.g.

static Button createButton(Frame f, String label, int x0, int y0, int width, int height) {
    Button b = new Button(label);
    b.setBounds(x0, y0, width, height);
    f.add(b);
    return b;
}


Then your code would simplify to lines like:

createButton(f, "+", 70, 100, 50, 40);


which is a reduction of roughly 2/3.

Of course this does not address the problem that you are trying to do pixel-exact layouts. You should rather be dropping elements on a grid which can be resized freely. (However, it has been a long time since I've used AWT so I can't give an example).

Code Snippets

static Button createButton(Frame f, String label, int x0, int y0, int width, int height) {
    Button b = new Button(label);
    b.setBounds(x0, y0, width, height);
    f.add(b);
    return b;
}
createButton(f, "+", 70, 100, 50, 40);

Context

StackExchange Code Review Q#40526, answer score: 14

Revisions (0)

No revisions yet.