6
\$\begingroup\$

This is the first code I've written. It's for an intro to Java course. Could you look over it and let me know of things I could improve before handing it in?

For reference, I've also provided what I'm being graded on at the bottom.

import java.util.Scanner;

public class LB01Smith {

    public static void main(String[] args) {
        System.out.println("This program computes the volume and surface area of a sphere, cube, and tetrahedron using a given dimension.");
        System.out.println("Next, the program will compute the dimension of a sphere, cube, and tetrahedron using a given volume.");
        Scanner input = new Scanner(System.in);
        String usersName;      
        String upperCaseName;  

        System.out.print("Please enter your name, then press ENTER: ");
        usersName = input.nextLine();

        upperCaseName = usersName.toUpperCase();

        System.out.println("Hello, " + upperCaseName + ", nice to meet you!");
        System.out.print(" ");
                double length = 0;
                double volume = 0;
                double cubeVolume = 0;
                double cubeSurfaceArea = 0;
                double sphereVolume = 0;
                double sphereSurfaceArea = 0;
                double tetVolume = 0;
                double tetSurfaceArea = 0;
                double cubeSide = 0;
                double sphereDiameter = 0;
                double tetSide = 0;
                final double PI = Math.PI;
                final double SQRT_2 = Math.sqrt(2);
                final double SQRT_3 = Math.sqrt(3);

                System.out.print("Please enter a dimension for volume calculation, then press ENTER: "); 
                length = input.nextDouble();

                cubeVolume = (length * length * length);
                cubeSurfaceArea = 6 * (length * length);

                sphereVolume = PI / 6 * (length * length * length);
                sphereSurfaceArea = 4 * PI * ((length / 2) * (length / 2));

                tetVolume = (length * length * length ) / (6 * SQRT_2);
                tetSurfaceArea = SQRT_3 * (length * length);

                System.out.println("");
                System.out.println("The Volume of your CUBE is : " + cubeVolume);
                System.out.println("The Surface Area of your CUBE is : " + cubeSurfaceArea);
                System.out.println("");
                System.out.println("The Volume of your SPHERE is : " + sphereVolume);
                System.out.println("The Surface Area of your SPHERE is : " + sphereSurfaceArea);
                System.out.println("");
                System.out.println("The Volume of your TETRAHEDRON is : " + tetVolume);
                System.out.println("The Surface Area of your TETRAHEDRON is : " + tetSurfaceArea);
                System.out.println("");

                System.out.print("Now, please enter a volume for side or diameter calculation, then press ENTER: ");
                volume = input.nextDouble();

                cubeSide = Math.pow(volume, (1.0/3.0));
                float roundedValue = Math.round(cubeSide);

                sphereDiameter = Math.pow(volume / PI * 6, (1.0/3.0));

                tetSide = SQRT_2 * Math.pow(3 * volume, (1.0/3.0));

                System.out.println("");
                System.out.println("The Side of your CUBE is : " + roundedValue);
                System.out.println("");
                System.out.println("The Diameter of your SPHERE is : " + sphereDiameter);
                System.out.println("");
                System.out.println("The Side of your TETRAHEDRON is : " + tetSide);
                System.out.println("");

                System.out.println("Closing Program...");
                input.close();
                System.out.println("The program has ended. Thank you, " + upperCaseName + ", Goodbye.");

    }
}

( __ / 1 ) You name your program LB01LastName, where you change the LastName to your own last name.

( __ / 2 ) Submit a copy of your source code (the .java file) .

( __ / 2 ) Your program tells the user what the program does.

( __ / 3 ) Your program prompts the user for a length dimension.

( __ / 6 ) Your program declares and uses constants for the square root of two, square root of three, and pi.

( __ / 6 ) Your program correctly calculates the volume and surface area of the cube.

( __ / 6 ) Your program correctly calculates the volume and surface area of the sphere with that length as its diameter.

( __ / 6 ) Your program correctly calculates the volume and surface area of the regular tetrahedron.

( __ / 6 ) Your program outputs the results of the area calculations.

( __ / 6 ) Your program outputs the results of the volume calculations.

( __ / 3 ) Your program prompts the user for a volume.

( __ / 6 ) Your program correctly calculates the side length of a cube with that volume.

( __ / 6 ) Your program correctly calculates the diameter of a sphere with that volume.

( __ / 6 ) Your program correctly calculates the side length of a tetrahedron with that volume.

( __ / 6 ) Your program outputs the results of the length calculations.

( __ / 2 ) Your program tells the user that it is terminating.

( __ / 6 ) Your code is easy to read because you followed the programming style outlined in section 1.10 of the text by Y. Daniel Lang.and made appropriate use of spaces, indentation, and blank lines.

( __ / 6 ) You followed the naming conventions outlined in section 2.8 of the text by Y. Daniel Lang.and used a class name that starts with a capital letter, variable names that are full and descriptive and start with a lower case letter, and constant names that are in all capital letters.

( __ / 6 ) Your code is well documented as outlined in section 1.10 of the text by Y. Daniel Lang.and has javadoc style comments before the class and main method.

( __ / 5 ) Your code is efficiently written.

( __ / 5 ) Extra Credit: Have your program prompt the user for a common area and then calculate the dimension for each shape to have that area.

\$\endgroup\$

3 Answers 3

4
\$\begingroup\$

Your program declares and uses constants

Generally constants are declared at the class level rather that the method level.

followed the programming style ... spaces, indentation, and blank lines

I'm fairly certain the extra tabs halfway through your main method are side-effects of Markdown, otherwise fix them to match the rest of the method.

Your string literals in System.out.print(ln) are excessively long. Older coding styles dictate 80 characters per line, personally, my team has agreed on 140 cpl. Going much beyond that leads to a lot of head shaking when trying the read the code. It's okay to split string literals with new lines and the + operator. javac will compile out the concatenation. Also, call System.out.println without the empty string to end a line or output a blank line. e.g:

System.out.println("This is a really long string " +
    "literal that the compiler will combine. " +
    "Just don't forget the trailing spaces.");
System.out.println();

If your class has not covered it, you can find a lot of useful information on formatting output here.

Some coding standards (and languages) require you to place all variable declarations at the top of the scope (class, method or block) while others (again, like my team's) prefer the declaration where it is first used. Find out which style the class prescribes and stick to it. Having a large block of declaration after all had output code is confusing.

\$\endgroup\$
3
\$\begingroup\$

Initializing variables when to values that will never be used and overwritten shortly after, is a bad practice. Furthermore, it's best to declare variables where you actually use them.

Close file handles immediately when you don't need them anymore, not later at some random point in code.

The indentation is incorrect:

  • inconsistent widths: sometimes 2, sometimes 4. You should use 4 always
  • unexpected indented block halfway through main

Echoing back the user's name in all uppercase letters is odd. If you want to print names "pretty", than it would be better to capitalize only the first letter of each name. But that might get more complicated than the rest of the program. Another option is so to just leave it alone, print the name as the user entered it.

\$\endgroup\$
1
\$\begingroup\$
final double PI = Math.PI;

I understand that you get two points for 'using a constant for the value of \$\pi\$', but generally speaking, I will avoid using names that are the same as the static fields that I will in turn rely on (Math.PI) as it may get ambiguous in larger codebases.

( __ / 6 ) Your code is well documented as outlined in section 1.10 of the text by Y. Daniel Lang.and has javadoc style comments before the class and main method.

@rolfl posted an excellent answer to another Java question about two months ago regarding comments and Javadoc, and I feel you should definitely have a read at that for your future assignments. Essentially, comments should explain the why, not the how, and if you can avoid using them through the use of properly-named variables or easy-to-understand code constructs, that is generally the more favored approach outside of academic assignments.

In your case, adding a Javadoc to main() is usually redundant as there's nothing much to explain for this arguably famous method. This brings me to one more thing...

To Infinity And Beyond!

You are probably at the stage where you don't have to use methods or under Object-Oriented Programming (OOP) yet, but I guess there's no harm giving you a glimpse of how your code can be restructured.

Instead of putting all your code within the main() method, you can 'group' lines of your code that work together and independent of the rest. For example, you can extract your calculation for a cube's volume out as the following:

/**
 * Calculates the volume of a cube, given the length of a side
 * @param  length length of the cube's side
 * @return the volume of the cube
 * @throws {@link IllegalArgumentException} if {@code length} is 0 or less
 */
private static int double getVolumeOfCube(double side) {
    if (side <= 0.0)) {
        throw new IllegalArgumentException("Length cannot be 0 or less.");
    }
    return side * side * side;
}

What I have illustrated here is a simple Javadoc example explaining:

  • The purpose of this method,
  • The arguments of this method,
  • The return value of this method, and
  • Any possible Exceptions that can be thrown (e.g. validation errors).

From the signature and body of the method, it is also clear how a single length input is used to calculate the volume. Using this method is easy:

System.out.println("The Volume of your CUBE is : " + getVolumeOfCube(length));

In this case, you can even eliminate the temporary cubeVolume variable.

\$\endgroup\$

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .