r/programminghelp • • Feb 04 '25

Java Stuck on this part... (FREE)

I'm currently learning Java and I'm trying to write a code that calculates the surface area, volume, and circumference of a sphere given it radius. Pretty simple stuff...but it's also asking for the units involved.

I have this so far:

import java.util.Scanner;

public class AreaVolume {

public static void main(String\[\] args) {

	double radius, surfaceArea, volume, circumference;

	double pi = 3.14159;

	String units;

	

	Scanner in = new Scanner(System.in);

	

	System.out.print("Enter the radius: ");			// Gets user input for the radius of the sphere

	radius = in.nextDouble();

	System.out.print("Enter the units (inches, feet, miles, etc.): ");	// Gets the units of the radius

	units = in.next();

	

	surfaceArea = (4 \* pi \* Math.pow(radius, 2));						// Calculates surface area

	volume = ((4 \* pi \* Math.pow(radius, 3) / 3));						// Calculates volume

	circumference = (2 \* pi \* radius);								// Calculates circumference

	

	System.out.println();				// Displays the surface area, volume, and circumference

	System.out.printf("Surface Area: %.3f\\n", surfaceArea);		// of sphere and the units

	System.out.printf("Volume: %.3f\\n", volume);

	System.out.printf("Circumference: %.3f\\n", circumference);

	

	in.close();

}

}

But I don't know how to include the units at the end of the number.

1 Upvotes

3 comments sorted by

1

u/edover Feb 05 '25

You just need to include another placeholder in your printf statements. You're already using %.3f to print the numeric value, so just add a %s in there and follow it up with a second parameter for the units like this:

System.out.printf("Surface Area: %.3f%s\r\n", surfaceArea, units);

1

u/RandoPandour Feb 05 '25 edited Feb 05 '25

I see.

It works now, but now I have minor issue:

In the output window, there's now an unnecessary space next to where "Volume".

ETA: Nvm, I found there was a space next to the line break after Surface Area. Thx man.

0

u/RandoPandour Feb 04 '25

BTW, I'm using Eclipse