Java Lab #2: Types and Expressions

  1. Create a new project in your Eclipse workspace named Lab02 with a class of the same name. Put a main method in that class. All of the code you will write for this lab goes inside the main method.

  2. In this lab you will write a program that adds two fractions. Here is a sample run of the program to give you an idea of its requirements.

            Fraction #1: 1 / 2
            Fraction #2: 2 / 3
            The sum is 7 / 6
          

    In the run above "Fraction #1:" and "Fraction #2:" are prompts printed by your program. The user enters "1/2" and "2/3." Your program then computes the sum by adding the fractions and outputs the result.

  3. To read the input you'll need to use a couple different methods of the Scanner class. The method nextInt() returns the next integer. The method next() returns the next "token" as a string. So to read the slash separator you can do something like

            String separator = input.next();
          
  4. Once you have your program working try it with various kinds of input. For example

    What is the behavior of your program in each of the cases above? Is it to your liking?

  5. Let's try to fix the case when something other than '/' is used to separate the numerator and denominator by having the program output an error message in that case. To do this you'll need to use an if statement like this

            if (separator.equals("/")) {
                // All is okay. Proceed with the computation normally.
            }
            else {
                // The separator was something undesirable.
                // Display an error message.
            }
          

    Keep in mind that there are two different fractions being input and thus two different separators to check.

Turn in your final program with appropriate comments. Be sure your name is on your submission.