Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Very Basic Calculator

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Very Basic Calculator

    Hello all.

    I'm a beginner in Java and I want to learn good programming habits.
    I've made a basic calculator program and I was wondering if I could have done something different or shortened something in it, or even add anything to it.
    The code works fine.

    Any help is appreciated.

    Thank you!
    public class JavaApplication27 {
     
        static int numOne, numTwo;
     
        static Scanner scanStr = new Scanner(System.in);
        static String userInput;
        static String yesOrNo;
     
        public static void main(String[] args) {
            do {
                Scanner scanInt = new Scanner(System.in);
     
                System.out.println("Please enter your first number: ");
                numOne = scanInt.nextInt();
     
                System.out.println("Please enter your second number: ");
                numTwo = scanInt.nextInt();
     
                //Called the method inside the same class
                calculate();
                tryAgain();
     
            } while (yesOrNo.equals("Yes"));
        }
     
        public static void calculate() {
     
            do {
                System.out.println("What would you like to do with these numbers?");
                System.out.println("Input a function (+,-,*,/)");
     
                userInput = scanStr.next();
                switch (userInput) {
                    case "+":
                        System.out.println("The answer is " + (numOne + numTwo));
                        break;
                    case "-":
                        System.out.println("The answer is " + (numOne - numTwo));
                        break;
                    case "*":
                        System.out.println("The answer is " + (numOne * numTwo));
                        break;
                    case "/":
                        System.out.println("The answer is " + (numOne / numTwo));
                        break;
                    default:
                        System.out.println("Invalid input");
                        break;
                }
            } while (!"+".equals(userInput) && !"-".equals(userInput)
                    && !"*".equals(userInput) && !"/".equals(userInput));
     
        }
     
        public static void tryAgain() {
     
            do {
                System.out.println("Would you like to try again?");
                System.out.println("Input 'Yes' or 'No'");
     
                yesOrNo = scanStr.next();
     
                if (yesOrNo.equals("Yes")) {
                    System.out.println("Okay!");
                }else if(yesOrNo.equals("No")){
                    System.out.println("Thank you for using me!");
                    System.exit(0);
                }
            } while (!"Yes".equals(yesOrNo));
        }
    }


  2. #2
    Member Abhilash's Avatar
    Join Date
    Jun 2014
    Location
    Kolkata, West Bengal, INDIA
    Posts
    108
    My Mood
    Busy
    Thanks
    5
    Thanked 10 Times in 10 Posts

    Lightbulb Re: Very Basic Calculator

    Good job! Sorry but no one is going to shorten it for you, and you shouldn't shorten it too.
    This program has been made by you, and you only. This is your identity and changing this program for a shorter one made by someone else means changing your identity. There is nothing wrong in this program. It's good, and you should think that way too, because you made this. Not me, not the moderator, you. So you should be proud of it.

    Still, if you want it shortened, do it yourself. Because you, are the programmer of this program. Again, good job and happy programming.

  3. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Very Basic Calculator

    Quote Originally Posted by Abhilash View Post
    Good job! ...

    Still, if you want it shortened, do it yourself. Because you, are the programmer of this program. Again, good job and happy programming.
    I appreciate your comment. I never thought of it that way. Coming into programming, I thought that there was a general way that people coded things. I don't want to do things the wrong way or did something that was considered bad coding practice. That's why I posted this in the first place.

    You really helped [:

    Thank.

  4. #4
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    726
    Thanks
    0
    Thanked 132 Times in 115 Posts

    Default Re: Very Basic Calculator

    Your code looks alright so far. For the size of the application that is.
    Of course it would be nicer to have it use classes and polymorphism because that would make it easier to maintain and extend.

    For example, what would you do if you wanted to add additional arithmetic operations? You would have to extend your switch-case statement and add additional cases.
    What would be "nicer" in my personal opinion would be to add new "Operation" objects to an internal list of available operations.

    Operations might look like this:
    public interface ArithmeticOperation {
        public int calculate(int firstArg, int secondArg);
        public String getSymbol();
    }
    The Addition could then look like this:
    public class Addition implements ArithmeticOperation {
        public int calculate(int firstArg, int secondArg) {
            return firstArg + secondArg;
        }
        public String getSymbol() {
            return "+";
        }
    }

    If you had several of these in a list you could then iterate over them and perform the right one depending on the user input and the "symbol" for the operation. For example:
    List<ArithmeticOperation> operations = getSupportedOperations();
    String input = scanStr.next();
    boolean operationAvailable = false;
    for (ArithmeticOperation op : operations) {
        if (op.getSymbol.equals(input) {
            int result = op.calculate(numOne, numTwo);
            // output result
            operationAvailable = true;
            break;
        }
    }
    if (!operationAvailable) {
        // tell user that operation is not available
    }
    Just a little suggestion.

    The benefit of this would be that your calculator itself is completed and never needs to be rewritten when new operations are to be added. Instead you only have to create a new Operation-Object which implements the new operation; then add it to a list of supported operations.

  5. #5
    Member Abhilash's Avatar
    Join Date
    Jun 2014
    Location
    Kolkata, West Bengal, INDIA
    Posts
    108
    My Mood
    Busy
    Thanks
    5
    Thanked 10 Times in 10 Posts

    Lightbulb Re: Very Basic Calculator

    Quote Originally Posted by DreamHacked View Post
    I appreciate your comment. I never thought of it that way. Coming into programming, I thought that there was a general way that people coded things. I don't want to do things the wrong way or did something that was considered bad coding practice. That's why I posted this in the first place.

    You really helped [:

    Thank.
    No problem. Just to add to your comment, there is no general way people code programs in java. And that's the fun of it, you can make programs the way you like. That's creates your identity as a programmer. Don't take anyone's suggestions, make programs your own way, the way you like.

    Now, to make this clear, your program wasn't at all any type of "bad coding practice". Impression is another thing. Some might like your program, some would prefer taking input of operand (+,-,*,/) before input of numbers, while some would prefer the applet version of the program. Doesn't matter. What matters is efficiency and working, i.e. how fast you can make programs and whether your program works for different circumstances (Eg:- if user inputs letters for numbers, if user inputs brackets, etc. which you should not worry about right now). Keeping these in mind, make your programs well. I myself have unique ways of making programs. I usually make programs in such a way nobody understands how I do it, what logic I use, but it always helps me make programs much quicker than a normal student (See my success story for details, it is in member introductions). So, do it your way, do it well. Because your programs are your identity. And that's what defines you.

    Thank you.

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,334
    Thanks
    181
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: Very Basic Calculator

    Quote Originally Posted by Abhilash View Post
    there is no general way people code programs in java...Don't take anyone's suggestions, make programs your own way, the way you like.
    While I agree that most problems have different solutions and it is up to the programmer to not only define those solutions but turn them into an implementation, there are guidelines that facilitate code maintenance, reuse, and readability.

    From a syntax standpoint, coding conventions make code more readable and maintainable (see Code Conventions for the Java Programming Language: Contents and Google Java Style). From a comment point of view, (note, the OP's code has no comments) the javadoc tool requires specific comment formatting to be able to read comment blocks and turn them into API docs. From a data and algorithm standpoint, there are established data structures and algorithms one can use. From an organizational standpoint, there are patterns one can rely on (aka design patterns) to facilitate code reuse and maintainability...and there are many other guidelines one can follow that I won't continue to mention.

    Of course, none of these are required and one can 'do it the way they like', but this is at the risk of being able to read, share, maintain, and reuse code to the best of one's abilities.

  7. The Following 3 Users Say Thank You to copeg For This Useful Post:

    Abhilash (June 12th, 2014), GregBrannon (June 11th, 2014), Wizand (June 12th, 2014)

  8. #7
    Member Abhilash's Avatar
    Join Date
    Jun 2014
    Location
    Kolkata, West Bengal, INDIA
    Posts
    108
    My Mood
    Busy
    Thanks
    5
    Thanked 10 Times in 10 Posts

    Default Re: Very Basic Calculator

    Well thank you. I'm really sorry but I didn't know the rules. Actually I was just giving DreamHacked advice regarding personal programming i.e. programming for projects, homework, etc. These rules apply for software engineers who make programs everyday and their programs need to be maintained and updated by others. I really didn't know the rules and I don't know about the others but it really did help me a lot. Although I'm just a student in a school but it will help me later in my life.

    Thank you.

  9. #8
    Junior Member
    Join Date
    Feb 2014
    Location
    Finland
    Posts
    25
    My Mood
    Bored
    Thanks
    3
    Thanked 5 Times in 5 Posts

    Default Re: Very Basic Calculator

    I have to bandwagon copeg here. Even tho Abhilash has a point in that each programmer has his/her own way of implementing things and one can often notice a certain style for each programmer, there definitely is conventions and so called "best practices" for programming in general and for each language in specific. And even on concept/task level ( for example best practices for socket programming in Java ). One can google for these and the result list is huge. Just remember to mirror the credentials of the writer to the claims - many of these articles have (probably) been written by people that don't really have the authority to give out best practices -advises ( e.g. Bjarne Stroustrup giving out tips on how to do stuff in C++ versus some newly graduated software engineer doing the same. You'd had to take the latter with a grain of salt. ).

    I have enjoyed the Steve McConnell's Code Complete SE book Code Complete, Second Edition | Microsoft having a good amount of good practices for programming in general. As well as the Clean Code -book http://www.amazon.com/Clean-Code-Han.../dp/0132350882 by Robert C. Martin. But everyone has their own favourites, right?

    Anyhow, your program seems fine to me for the scope of it, no worries . Shortness of program isn't always a virtue either, at least if the size doesn't add to performance too much.

Similar Threads

  1. simple basic calculator
    By kassie hans in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 16th, 2014, 04:42 AM
  2. Problem with basic calculator - Beginner
    By Dream Hacked in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 25th, 2013, 11:00 PM
  3. A basic calculator
    By SathApoc in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 22nd, 2011, 11:47 AM
  4. having bad time with basic calculator code
    By hashey100 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 12th, 2011, 08:29 PM
  5. Basic Calculator
    By Yes. in forum What's Wrong With My Code?
    Replies: 13
    Last Post: June 4th, 2010, 04:24 PM