Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 basic calculator
Index -> Programming, Java -> Java Submissions
Goto page 1, 2, 3  Next
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
cool dude




PostPosted: Wed May 03, 2006 5:25 pm   Post subject: basic calculator

this is my first program in java! Smile can u guys please tell me a lot of feedback on how i can improve. i.e. better coding style, indents correct?, better variable names, simpler ways of doing things, etc.

code:

import java.io.*;
public class calculator
{
    public static void main (String[] args)
    {
        BufferedReader in;
        PrintStream out;
        String snum1;       //stores the first number
        String snum2;       //stores the second number
        String operation;   //stores the operation user chose
        int inum1;          //stores the converted integer number
        int inum2;          //stores the converted integer number
        int sum;            //stores the sum of the numbers
        int subtraction;
        int product;
        int quotient;
       
        try
        {
           
        in = new BufferedReader(new InputStreamReader(System.in));
        out = System.out;

        //asks for input from user - 2 numbers and operation
        System.out.println("Enter first number");
        snum1 = in.readLine();
        System.out.println("Enter second number");
        snum2 = in.readLine();
        System.out.println ("Enter the operation you want");
        System.out.println ("A - Addition");
        System.out.println("S - Subtraction");
        System.out.println ("M - Multiplication");
        System.out.println("D - Division");
        operation = in.readLine();
       
        //converts the string numbers to integer
        inum1 = Integer.parseInt(snum1);
        inum2 = Integer.parseInt(snum2);
       
        if (operation.equals ("A")){
            sum = inum1 + inum2;
            System.out.println("the sum of the numbers is " + sum);
        }else if (operation.equals ("S")){
            subtraction = inum1 - inum2;
            System.out.println("The subtracted numbers is equal to " + subtraction);
        }else if (operation.equals ("M")){
            product = inum1 * inum2;
            System.out.println("The product of the numbers is " + product);
        }else if(operation.equals ("D")){
            quotient = inum1/inum2;
            System.out.println("The quotient is " + quotient);
        }
 
           
        }catch (NumberFormatException nfe){
        System.out.println("can't convert: ");
   
    }
        catch(IOException f){
             System.err.println("some error");
    }

}
}
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Wed May 03, 2006 5:40 pm   Post subject: (No subject)

  • Place a blank line between imports and the following code.
  • Class names always begin with an uppercase letter.
  • The brace following "public class calculator" should be on the same line, separated by a space. Java doesn't enforce this, but it is suggested by Sun's Java style guidelines. This should be done with methods and constructs like "if", "for" and "try" as well.
  • The parenthesis following a method name like "main" should immediately follow it. No spaces.
  • You should indent the contents of the try block.
  • Your try block is surrounding the contents of the entire method, rather than the code which generates the NumberFormatException. This is phenomenally bad practice to get into the habit of.
  • You are separately declaring and initializing your variables. You do not need to do this.

    code:
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

  • You have a useless alias of System.out. In fact, you don't even use this alias later on in the program.

    In Java 1.5.0 you can achieve this with a static import, if you must.

    code:
    import static java.lang.System.out;


    You should use this very judiciously.
  • Instead of numerous ifs and elses, you should simply use a switch statement on the first character in the string.
cool dude




PostPosted: Wed May 03, 2006 7:51 pm   Post subject: (No subject)

k i fixed most of it up but i just have a couple questions.

Quote:
Your try block is surrounding the contents of the entire method, rather than the code which generates the NumberFormatException. This is phenomenally bad practice to get into the habit of.


wat does that mean? Confused


Quote:

You are separately declaring and initializing your variables. You do not need to do this.


do u mean just declare all the variables on one line?



Quote:

You have a useless alias of System.out. In fact, you don't even use this alias later on in the program.


to tell u the truth i didn't really know wat it was for. when i was trying to learn user input thats how it was shown to me so i kinda thought u need it. Embarassed when would u need it???



Quote:

Instead of numerous ifs and elses, you should simply use a switch statement on the first character in the string


wats a switch statement?


Thanks a lot for all the suggestions! Smile now i could get into the habbit of coding better. Also thanks for the great tutorial i am learning a lot from it! Smile
wtd




PostPosted: Wed May 03, 2006 8:12 pm   Post subject: (No subject)

cool dude wrote:
k i fixed most of it up but i just have a couple questions.

Quote:
Your try block is surrounding the contents of the entire method, rather than the code which generates the NumberFormatException. This is phenomenally bad practice to get into the habit of.


wat does that mean? Confused


When you catch an exception, you wish to keep it as tight as possible. If you have three statements and only one which can throw an Exception, for instance:

code:
try {
   a();
   b();
   c();
}
catch (Exception e) {
   // ...
}


Is bad.

code:
a();

try {
   b();
}
catch (Exception e) {
   // ...
}

c();


Is better.

Quote:
Quote:

You are separately declaring and initializing your variables. You do not need to do this.


do u mean just declare all the variables on one line?


No, I do not. Do you understand what delaration and initialization are?

Quote:

Quote:

You have a useless alias of System.out. In fact, you don't even use this alias later on in the program.


to tell u the truth i didn't really know wat it was for. when i was trying to learn user input thats how it was shown to me so i kinda thought u need it. Embarassed when would u need it???


You would probably never need such a thing. You could use it if you wanted a shorter name to type, but it's more important to focus on having meaningful names.


Quote:

Quote:

Instead of numerous ifs and elses, you should simply use a switch statement on the first character in the string


wats a switch statement?


Read up, then tell me. Wink


Quote:
Thanks a lot for all the suggestions! Smile now i could get into the habbit of coding better. Also thanks for the great tutorial i am learning a lot from it! Smile


You're welcome.
cool dude




PostPosted: Wed May 03, 2006 9:10 pm   Post subject: (No subject)

k thanks again. i'm still not sure wat u mean by the catch exception? do u mean have a catch exception after every input i get so if i get the wrong input it will catch it imediately instead of at the end?

also yes i know wat the difference between variables and initializing them is! srry i kinda read your post quickly so i thought it just said variables Embarassed i understand u mean something like this

code:

int seven = 7


but i don't understand where i would do that in my code Confused Confused

also should i put the catch exception in a loop? because if it finds an error it would stop the program and i want it to repeat the question?

P.S. is there a clear command to clear the whole screen? as well as an exit command? i tried searching but didn't come up with much
wtd




PostPosted: Wed May 03, 2006 9:19 pm   Post subject: (No subject)

Clearing the screen in Turing is a trick based on the fact that Turing's output window is a graphics window. Java's standard output is an actual text IO window.
cool dude




PostPosted: Wed May 03, 2006 9:22 pm   Post subject: (No subject)

wtd wrote:
Clearing the screen in Turing is a trick based on the fact that Turing's output window is a graphics window. Java's standard output is an actual text IO window.


so your saying there is no way to clear the screen in java? Confused

anyways i read on switch statements and they seem like cases although i didn't really ever use cases so i'm not too sure how to do them. this is wat is says:

Quote:

The switch statement evaluates an integer or enumerated type expression and executes the appropriate case statement.
switch (integer expression) {
case integer expression:
statement(s)
break;
...
default:
statement(s)
break;
}

switch (expression of enum type) {
case enum constant:
statement(s)
break;
...
default:
statement(s)
break;
}



i don't really understand this mind explaining or providing a link that explains this better?
wtd




PostPosted: Wed May 03, 2006 9:28 pm   Post subject: (No subject)

cool dude wrote:
wtd wrote:
Clearing the screen in Turing is a trick based on the fact that Turing's output window is a graphics window. Java's standard output is an actual text IO window.


so your saying there is no way to clear the screen in java? Confused


For standard output in Java, no, there is no reliable way to clear the screen.

Quote:
anyways i read on switch statements and they seem like cases although i didn't really ever use cases so i'm not too sure how to do them. this is wat is says:

Quote:

The switch statement evaluates an integer or enumerated type expression and executes the appropriate case statement.
switch (integer expression) {
case integer expression:
statement(s)
break;
...
default:
statement(s)
break;
}

switch (expression of enum type) {
case enum constant:
statement(s)
break;
...
default:
statement(s)
break;
}



i don't really understand this mind explaining or providing a link that explains this better?


code:
int something = ...; // something

if (something == somethingElse) {
   // ...
}
else if (something == somethingElseEntirely) {
   // ...
}
else {
   // ...
}


code:
int something = ...; // something

switch (something) {
   case somethingElse:
      // ...
      break;
   case somethingElseEntirely:
      // ...
      break;
   default:
      // ...
      break;
}
Sponsor
Sponsor
Sponsor
sponsor
cool dude




PostPosted: Wed May 03, 2006 9:56 pm   Post subject: (No subject)

thanks i understand switch statements now Smile the only problem i'm having is that i'm working with string values i.e. "A" - Addition, "M" - Multiplication, etc. and it tells me incompatible types, thus i think i have to work with integers because then it works. i know how to convert to integers but the problem is the values are letters not numbers so how do i make a case with strings?
wtd




PostPosted: Wed May 03, 2006 10:07 pm   Post subject: (No subject)

The switch statement doesn't work with strings.

But chars are just a type of integer... Wink
cool dude




PostPosted: Wed May 03, 2006 10:47 pm   Post subject: (No subject)

wtd wrote:
The switch statement doesn't work with strings.

But chars are just a type of integer... Wink


i tried chars but then i run into an error because when i'm reading userinput in.readline() it says incompatible types. it can only read strings so i can't declare operation as char. i'm a little lost?
wtd




PostPosted: Wed May 03, 2006 11:03 pm   Post subject: (No subject)

How would you go about getting a specific character from a string?
cool dude




PostPosted: Wed May 03, 2006 11:07 pm   Post subject: (No subject)

wtd wrote:
How would you go about getting a specific character from a string?


i'm guessing using something like mid in visual basic. right? Confused
[Gandalf]




PostPosted: Wed May 03, 2006 11:18 pm   Post subject: (No subject)

How about like:
code:
var name : string := "bafd"
put name (1)

Just in Java? Why don't you look at the java documentation for the String class for a method which does just this.
cool dude




PostPosted: Wed May 03, 2006 11:25 pm   Post subject: (No subject)

[Gandalf] wrote:
How about like:
code:
var name : string := "bafd"
put name (1)

Just in Java? Why don't you look at the java documentation for the String class for a method which does just this.


wow i didn't even know u can do that in turing! Embarassed anyhow i have no clue wat u guys r talking about Confused basically the problem is that i can't use switch with strings. so i need to somehow pass integers. now u guys are telling me to take each letter seperately for wat? the user already enters only 1 letter. i don't think i'm understanding wat u guys are trying to say. Confused Confused
Display posts from previous:   
   Index -> Programming, Java -> Java Submissions
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 3  [ 38 Posts ]
Goto page 1, 2, 3  Next
Jump to:   


Style:  
Search: