Computer Science Canada

basic calculator

Author:  cool dude [ 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");
    }

}
}

Author:  wtd [ Wed May 03, 2006 5:40 pm ]
Post 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.

Author:  cool dude [ Wed May 03, 2006 7:51 pm ]
Post 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

Author:  wtd [ Wed May 03, 2006 8:12 pm ]
Post 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.

Author:  cool dude [ Wed May 03, 2006 9:10 pm ]
Post 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

Author:  wtd [ Wed May 03, 2006 9:19 pm ]
Post 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.

Author:  cool dude [ Wed May 03, 2006 9:22 pm ]
Post 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?

Author:  wtd [ Wed May 03, 2006 9:28 pm ]
Post 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;
}

Author:  cool dude [ Wed May 03, 2006 9:56 pm ]
Post 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?

Author:  wtd [ Wed May 03, 2006 10:07 pm ]
Post subject: 

The switch statement doesn't work with strings.

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

Author:  cool dude [ Wed May 03, 2006 10:47 pm ]
Post 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?

Author:  wtd [ Wed May 03, 2006 11:03 pm ]
Post subject: 

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

Author:  cool dude [ Wed May 03, 2006 11:07 pm ]
Post 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

Author:  [Gandalf] [ Wed May 03, 2006 11:18 pm ]
Post 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.

Author:  cool dude [ Wed May 03, 2006 11:25 pm ]
Post 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

Author:  wtd [ Wed May 03, 2006 11:30 pm ]
Post subject: 

You need to think abstractly.

Switch works on integer type expressions ->
The char type is a sort of integer ->
Switch works on chars.

You have a String type expression.
You need to deal with one character from that string.
If you can get that character, you're set.

Author:  rizzix [ Thu May 04, 2006 11:54 am ]
Post subject: 

Hmm, I'd suggest to keep the model and view separate.You see, that would work, but it would require a redesign when you decide to change to use _words_ to represent numbers (like "One" for 1), or if you internationalise it, etc.

Author:  cool dude [ Thu May 04, 2006 4:09 pm ]
Post subject: 

k i thought about it and this is wat i think... take the Ascii value of the letter, thus u will have an integer that u can work with. the only problem though is i have no idea how i would take the Ascii value of the letter? also wouldn't that be more code, more troubles and if statements would be better? why is it better to use switch cases instead of if statements?

Author:  wtd [ Thu May 04, 2006 4:17 pm ]
Post subject: 

In the switch statement you only state the name of the variable you're matching against once, and you don't write the == operator each time. This prevents typos, and the == operator can easily be confused with the = operator, which has dramatically different results.

Remember: all other things being equal, the more code you write, the more likely you are to screw something up. Smile

As for strings...

code:
String foo = "hello";
... bar = foo[0];

System.out.println(bar);


Fill in the ... part and tell me what the call to System.out.println prints.

Author:  cool dude [ Thu May 04, 2006 4:36 pm ]
Post subject: 

i hava no clue wat you are doing here? Confused i guess it print watever value bar is although i don't know wat bar even means? Confused also how does this relate to wat we r talking about?

Author:  wtd [ Thu May 04, 2006 4:51 pm ]
Post subject: 

A string is a series of characters. You need to be able to get just one of those characters out of a string. This what I'm trying to explain.

Author:  cool dude [ Thu May 04, 2006 5:22 pm ]
Post subject: 

is this wat u mean?

code:

String hello = ("Hello");
System.out.println (hello.charAt(0));


if i do the same thing with the operation variable i could use it now as switch so thats good Smile but now when i say case "A", case "B", etc. it says incompatible types.

this is the part of the code

code:

operation2 = operation.charAt(0);

switch(operation2){
                case "A":
                    sum = inum1 + inum2;
                    System.out.println("the sum of the numbers is " + sum);
                    break;
                case "S":
                    subtraction = inum1 - inum2;
                    System.out.println("The subtracted numbers is equal to " + subtraction);
                    break;
                case "M":
                    product = inum1 * inum2;
                    System.out.println("The product of the numbers is " + product);
                    break;
                case "D":
                      quotient = inum1/inum2;
                      System.out.println("The quotient is " + quotient);
                      break;
                    }

Author:  wtd [ Thu May 04, 2006 5:44 pm ]
Post subject: 

Is "A" of type char?

Author:  cool dude [ Thu May 04, 2006 6:05 pm ]
Post subject: 

wtd wrote:
Is "A" of type char?
"A" is not of type char its of type string but then how do i take "A" and change it to type char? or do i have to do exactly wat i did with operation2? i.e make more variables and declare them of type char and then convert "A" into type char? (i tried doing that but it doesn't work)

***Edit*** did i convert operation into char correctly? is that how u do it?

Author:  wtd [ Thu May 04, 2006 7:08 pm ]
Post subject: 

How did you declare operation2? If you don't know what I mean by "declare", then you have considerable fundamental reading to do.

Author:  cool dude [ Thu May 04, 2006 7:40 pm ]
Post subject: 

wtd wrote:
How did you declare operation2? If you don't know what I mean by "declare", then you have considerable fundamental reading to do.


obviosly i know wat u mean by declare i know turing and VB so i think i know wat declare is. i declared operation2 as char.

code:

char operation2;

Author:  wtd [ Thu May 04, 2006 7:50 pm ]
Post subject: 

I "knew" a lot before I knew much of anything, so I try not to assume. Wink

When in doubt, test with small apps.

code:
public class CharTest {
   public static void main(String[] args) {
      String foo = "foo";
      char bar = foo[0];
      System.out.println(bar);
   }
}

Author:  cool dude [ Thu May 04, 2006 8:24 pm ]
Post subject: 

is the code supposed to not work? and can u be a little more descriptive because i think i'm a little lost on wat we r trying to do Confused

Author:  wtd [ Thu May 04, 2006 8:32 pm ]
Post subject: 

If you want to figure out how fundamental little things like accessing characters in a string work, do so in a simple test app. That way you can be sure any flaws that might be in your larger program aren't distracting you.

Remeber, any complex problem is just a collection of smaller, simpler problems. Smile

Author:  cool dude [ Thu May 04, 2006 10:43 pm ]
Post subject: 

wtd wrote:
If you want to figure out how fundamental little things like accessing characters in a string work, do so in a simple test app. That way you can be sure any flaws that might be in your larger program aren't distracting you.

Remeber, any complex problem is just a collection of smaller, simpler problems. Smile


thanks for the advice i usually do that especially when learning a new language. Smile when i tried that code u gave in a simple test app. it did not work and said array required. Confused anyhow wat is it supposed to do?

Author:  wtd [ Thu May 04, 2006 10:47 pm ]
Post subject: 

Ah, probably should have been:

code:
public class CharTest {
   public static void main(String[] args) {
      String foo = "foo";
      char bar = foo.charAt(0);
      System.out.println(bar);
   }
}


I was thinking the String class had a bit of syntactic sugar that it doesn't.

Author:  cool dude [ Fri May 05, 2006 3:04 pm ]
Post subject: 

k this is wat i did but the only problem now is it says constant expression required Confused

code:

 //converts string into char in order to use in switch cases
            String lettera = "A";
            char a = lettera.charAt(0);
           
            String letters = "S";
            char s = letters.charAt(0);
           
            String letterm = "M";
            char m = letterm.charAt(0);
           
            String letterd = "D";
            char d = letterd.charAt(0);
           
            switch(operation2){
                case a:
                    sum = inum1 + inum2;
                    System.out.println("the sum of the numbers is " + sum);
                    break;
                case s:
                    subtraction = inum1 - inum2;
                    System.out.println("The subtracted numbers is equal to " + subtraction);
                    break;
                case "M":
                    product = inum1 * inum2;
                    System.out.println("The product of the numbers is " + product);
                    break;
                case "D":
                      quotient = inum1/inum2;
                      System.out.println("The quotient is " + quotient);
                      break;
                    }

Author:  wtd [ Fri May 05, 2006 3:13 pm ]
Post subject: 

Character constants can be represented in Java with single quotes.

Author:  cool dude [ Fri May 05, 2006 4:15 pm ]
Post subject: 

thanks a lot for all the help! Smile i took all your suggestions and fixed up my program. the only suggestion i can't do is the catch statement because if i put it after the code that is supposed to check if there is an error it doesn't work. it gives me an error saying the next code(after the catch statement) is not initialized or declared Confused

code:

import java.io.*;

public class Calculator {
    public static void main(String[] args) {
        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;    //stores the subtracted value
        int product;        //stores the product of the numbers
        int quotient;       //stores the quotient of the numbers
        char operation2;    //stores the operation as char type
       
        try {
           
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   
            //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();
            operation2 = operation.charAt(0);
           
            //converts the string numbers to integer
            inum2 = Integer.parseInt(snum2);
            inum1 = Integer.parseInt(snum1);
           
            switch(operation2){
                case 'A':
                    sum = inum1 + inum2;
                    System.out.println("the sum of the numbers is " + sum);
                    break;
                case 'S':
                    subtraction = inum1 - inum2;
                    System.out.println("The subtracted numbers is equal to " + subtraction);
                    break;
                case 'M':
                    product = inum1 * inum2;
                    System.out.println("The product of the numbers is " + product);
                    break;
                case 'D':
                      quotient = inum1/inum2;
                      System.out.println("The quotient is " + quotient);
                      break;
                    }
               
                }catch (NumberFormatException nfe){
                    System.out.println("can't convert: ");
                }catch(IOException f){
                    System.out.println("error reading input");
                }       
            }
        }

Author:  wtd [ Fri May 05, 2006 4:28 pm ]
Post subject: 

Let's clean up your indenting a bit.

code:
import java.io.*;

public class Calculator {
   public static void main(String[] args) {
      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;    //stores the subtracted value
      int product;        //stores the product of the numbers
      int quotient;       //stores the quotient of the numbers
      char operation2;    //stores the operation as char type
       
      try {
         BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));
   
         //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();
         operation2 = operation.charAt(0);
           
         //converts the string numbers to integer
         inum2 = Integer.parseInt(snum2);
         inum1 = Integer.parseInt(snum1);
           
         switch (operation2) {
            case 'A':
               sum = inum1 + inum2;
               System.out.println("the sum of the numbers is " + sum);
               break;
            case 'S':
               subtraction = inum1 - inum2;
               System.out.println("The subtracted numbers is equal to " +
                  subtraction);
               break;
            case 'M':
               product = inum1 * inum2;
               System.out.println("The product of the numbers is " +
                  product);
               break;
            case 'D':
               quotient = inum1/inum2;
               System.out.println("The quotient is " + quotient);
               break;
         }         
      }
      catch (NumberFormatException nfe) {
         System.out.println("can't convert: ");
      }
      catch (IOException f) {
         System.out.println("error reading input");
      }       
   }
}


Now, a few important things about exception handling for you to realize:

  • You can have more than one try { ... } catch { ... } construct in a method. You can even have one inside another.
  • Variables declared inside a try block are local to that block. They do not exist outside of it. This is known as "scoping" and is vitally important to understand.

Author:  cool dude [ Fri May 05, 2006 4:39 pm ]
Post subject: 

k so to get this clear. first do u only have one try{...} block and then inside it have as many catch{...} blocks as u need? or do you have a try{...} and catch{...} block for every time u need it? also if i have variables inside the try block does that mean there is no way of getting there values outside of that try block?

Author:  wtd [ Fri May 05, 2006 4:48 pm ]
Post subject: 

Well, the catch blocks always accompany a try block. That is the relationship between them. The try block tries to execute some code, and the catch blocks catch specific classes of exceptions (NumberFormatException for instance).

COnsider the following psuedocode:

code:
try {
   try {

   }
   catch {

   }
}
catch () {

}
catch () {

}

try {

}
catch {

}


And you're correct. A variable declared inside a try block does not exist outside of that block. It also does not exist within the associated catch blocks.

If you need to get at a variable from outside of that block, then you must declare it outside of that block. Consider carefully the scope your variables actually need.

Author:  cool dude [ Fri May 05, 2006 5:10 pm ]
Post subject: 

i'm trying to put a try and catch block after every input. i.e. get first number so i have a try and catch block around that checking to see if its valid and then the same thing with the second number and the operation but then when i get to my switch statement it says the variable has not been initialized. so how can i have a try and catch block around each input if its going to say at my switch statement that the variable is not initialized? Confused the only way it works is by me having one try block and at the end have the catch blocks


: