I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...
Related
I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.
All I need it to do is loop again so the user can continuously use the program if they to. Let me know if there are any reference that I can read up to, to help me understand more about this problem. Thanks in advance.
import java.util.Scanner;
public class Module3Assignment1 {
// public variables
public static String letterChosen;
public static int loop = 0;
public static double radius, area;
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// tells user what the program is about
System.out.println("Welcome to the Round Object Calculator");
System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
System.out.println("The calculations will be based on the user input radius.");
System.out.println("");
// loops while the user wants to calculate information
while (loop == 0){
Input();
System.out.print(Answer());
System.out.println("Do you want to calculate another round object (Y/N)? ");
String input = scanner.next().toUpperCase();
if (input == "N"){
loop = 1;
}
}
// ending message/goodbye
Goodbye();
scanner.close();
}
private static void Input(){
// prompts user for input
System.out.print("Enter C for circle or S for sphere: ");
letterChosen = scanner.nextLine().toUpperCase();
System.out.print("Thank you. What is the radius of the circle (in inches): ");
radius = scanner.nextDouble();
}
private static double AreaCircle(){
// calculates the area of a circle
area = Math.PI * Math.pow(radius, 2);
return area;
}
private static double AreaSphere(){
// calculates the area of a sphere
area = (4/3) * (Math.PI * Math.pow(radius, 3));
return area;
}
private static String Answer(){
//local variables
String answer;
if(letterChosen == "C"){
// builds a string with the circle answer and sends it back
answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", AreaCircle(), "inches");
return answer;
}else{
// builds a string with the sphere answer and sends it back
answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", AreaSphere(), "cubic inches");
return answer;
}
}
private static String Goodbye(){
// local variables
String goodbye;
// says and returns the goodbye message
goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
return goodbye;
}
}
The below is the console output and the error I am getting after execution
Welcome to the Round Object Calculator
This program will calculate the area of a circle of the colume of a sphere.
The calculations will be based on the user input radius.
Enter C for circle or S for sphere: C
Thank you. What is the radius of the circle (in inches): 12
The volume of a sphere with a radius of 12.000000 inches is: 5428.672 cubic inches
Do you want to calculate another round object (Y/N)?
Y
Enter C for circle or S for sphere: Thank you. What is the radius of the circle (in inches): C
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at Module3Assignment1.Input(Module3Assignment1.java:48)
at Module3Assignment1.main(Module3Assignment1.java:24)
import java.util.Scanner;
public class Module3Assignment1 {
// public static variables are discouraged...
private static char letterChosen; //char takes less memory
private static char useAgain = 'Y'; //just use the answer to loop...
private static double radius, area;
private static String answer;
private static Scanner scanner = new Scanner(System.in);
//you might want to clear the screen after the user gave an answer to another round object
private static void clearScreen(){
for(int i =0;i<50;i++){System.out.print("\n");}
}
public void input(){
// prompts user for input
System.out.print("Enter C for circle or S for sphere: ");
letterChosen = scanner.next().charAt(0);
System.out.print("Thank you. What is the radius of the circle (in inches): ");
radius = scanner.nextDouble();
this.answer= answer(letterChosen);
}
public double areaCircle(double radius){
// calculates the area of a circle
area = Math.PI * Math.pow(radius, 2);
return area;
}
public double areaSphere(double radius){
// calculates the area of a sphere
area = (4/3) * (Math.PI * Math.pow(radius, 3));
return area;
}
public String answer(char letterChosen){
//local variables
String answer = "";
if(letterChosen=='c'||letterChosen=='C'){
answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", areaCircle(radius), "inches");
}else{
answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", areaSphere(radius), "cubic inches");
}
return answer;
}
private static String goodbye(){
// local variables
String goodbye;
// says and returns the goodbye message
goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye");
return goodbye;
}
public static void main(String[] args) {
// tells user what the program is about
System.out.println("Welcome to the Round Object Calculator");
System.out.println("This program will calculate the area of a circle of the colume of a sphere.");
System.out.println("The calculations will be based on the user input radius.");
System.out.println("");
Module3Assignment1 ass1 = new Module3Assignment1();
// loops while the user wants to calculate a round object
while (useAgain == 'Y'||useAgain=='y'){
ass1.input();
System.out.print(answer);
System.out.println("Do you want to calculate another round object (Y/N)? ");
useAgain = scanner.next().charAt(0);
System.out.println(useAgain);
clearScreen();
}
// ending message/goodbye
System.out.println(goodbye());
scanner.close();
}
}
Some things that I changed:
I used char instead of String. String takes up more memory than char.
added clearScreen() method which "clears" the screen when you're using console.
I added a parameter radius to areaSphere and areaCircle methods. This makes the methods reusable.
I changed all the public static variables to private static. using public static variables is HIGHLY DISCOURAGED. You may read this to find out why.
and to prevent public static variables, I created an instance of Module3Assignment1 instead of having everything in static.
changed the casing of method names. Please follow camel-casing, which means that the first letter of the method is lowercase and the other words will have the first letter in uppercase (e.g. input(), areaSphere() )
A comment about comparing Strings:
== compares REFERENCES TO THE OBJECT , NOT VALUES
use .equals() or .equalsIgnoreCase() if you want to compare the values of two Strings. here is a sample syntax:
if(string1.equals(string2)){
//do something
}
Concept One
Always use .equals Method while Comparing String in Java
So
if(letterChosen == "C")
Should be if(letterChosen.equals("C")) and so the Others
Concept Two.
This might be one of the reason that is happening with your code . You have already taken a UserInput from the keyboard object of the scanner class that's why it's giving the else response. This particularly happens when you take other than String input from that object
Thats because the Scanner#nextDouble method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.
WorkAround Fire a blank Scanner#nextLine call after Scanner#nextDouble to consume newline.
Or Use Two Scanner Object.
Demo What Happens With Same Scanner Object for Both nextLine() and nextInt()
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
int n=keyboard.nextInt();
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
Output
5
Invalid response.
now change the code structure to get String Input from that scanner Object and not get another kind of data types the code works.
With String as previous Input
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
String n=keyboard.nextLine();
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
Output
j
y
Great! Let's get started.
Without any previous response with that object your code will work.
public class Test {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
String userResponse;
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + "" + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
}
}
and Gives me the desired output
y
Great! Let's get started.
I usually have been doing this whole time creating two OBJECT of Scanner Class one to get String Input and other to get other data types Input
(Too be frank even i have been not able to figure out why i needed to create two Object's for receiving String and Other data types in java without any error. If anyone know please let me know )
I have been struggling with this issue for weeks and still cannot get what I need. My CalculatingRocketFlightProfile class holds the constructor with the parameters (totalImpulse, averageImpulse etc...) and the methods which calculates the outputs. My MAIN class has an object which inherits my keyboard entry class. This allows users to input a number. Now, all I need is to use these inputs and calculate a result (using the methods in the CalculatingRocketFlightProfile class) to be displayed. However my object of CalculatingRocketFlightProfile class wont acceppt any parameters or I simply doing something wronng. Please help me out I'm really frustrated.
//CalculatingRocketFlightProfile class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle; //declare variables to store results of calculations
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Setting the parameters
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Mutators - SET
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
public void setTheVehiclesMaximumVelocity(double theVehiclesMaximumVelocity) {
this.theVehiclesMaximumVelocity = theVehiclesMaximumVelocity;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.totalImpulse1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.averageImpulse2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.timeEjectionChargeFires3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.massEmptyVehicle4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.engineMass5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.fuelMass6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass ); //This will give me an error "cant find variables"
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry class (Same for all methods e.g. averageImpulse2, timeEjectionChargeFires3 etc...)
public class kbentry{
double totalImpulse1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
You are not storing the returned information from your kbentry methods. Try this:
System.out.print("\nPlease enter a number for Total Impulse: " );
double totalImpulse = input.totalImpulse1();
System.out.println("You have entered : " + totalImpulse);
Do the same for the other variables, then use those to pass in as arguments for your new object.
I am trying to design and implement a Java class to represent a 3-D geometric shape. The class should contain a constructor, appropriate data fields and methods to return the volume of the shape, and the surface area of the shape and any other methods that seem to make sense for your shape.
However, I got everything to work fine in Net Beans, but when I try to run it in the command prompt I receive:
error package Cube doesn't exist
error cannot find symbol
both of these error are referring to the class cube
My code is as follows.
package cube;
public class Cube {
private double side = 0.0;
public Cube(){//begin constructor
side = 1.0;
}//end constructor
public void setSide (double length) {//begin method
side = length;
}//end method
public double getSide () {//begin method
return side;
}//end method
public double calculateVolume() {
double volume2 = side * side * side;
return volume2;
} // end method
public double calculateSurfaceArea() {
double area = 6 * (side * side);
return area;
} // end method
}//end class
package randygilmanhw4;
import java.util.Scanner;
import cube.Cube;//imports class Cube
public class RandyGilmanHW4 {
public static void main(String[]args) {//begin main
//Display welcome message
System.out.println("Hello Welcome to Randy's Cube");
System.out.println(" Calculator Program");
System.out.println("");
Cube one = new Cube();
//declare variables within main
double area;
double volume2;
double side1;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a length of the side of the cube in cm: ");
side1 = input.nextDouble();
one.setSide(side1);
volume2 = one.calculateVolume();
System.out.printf("Cube's volume is: %4.2f cm^3", volume2);// OUTPUT
System.out.println("\n");
one.setSide(side1);
area = one.calculateSurfaceArea();
System.out.printf("Cube's surface area is: %4.2f cm^2 ", area);// OUTPUT
} // end main
}//end class
Simple - when you save it into a .java file, remove the line "package cube;" and save. It should now work - "package" is used for your IDE, not with notepad/cmd prompt. Save your file as RandyGilmanHW4.java
import java.io.*;
import java.util.*;
public class volumeConeD
{//class
public static void main (String [] args)
{//main
Scanner keyBoard = new Scanner(System.in);//input for keyBoard
//variables
double volume;
double radius;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{//begin of try
while(r == true){
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println ();
System.out.println ();
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble ();
//math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf ("Volume = " + volume);
}//end of try
catch (Exception Error){
System.out.println("You entered wrong data");
}
System.out.println ();
System.out.print("Does the user wish to try again?");
System.out.println ();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}//end of while
}//end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}//end of program
this is my first time posting on this forum, so please excuse how ask...here goes... all i am trying to do with this is repeat this problem under user control using a sentinel method(while loop). I had it almost working earlier but i kept getting errors about how i defined "r". Now i get errors about my catch try blocks. please help.
volumeConeD.java:35: error: 'catch' without 'try'
catch (Exception Error){
^
volumeConeD.java:35: error: ')' expected
catch (Exception Error){
^
volumeConeD.java:35: error: not a statement
catch (Exception Error){
^
volumeConeD.java:35: error: ';' expected
catch (Exception Error){
^
volumeConeD.java:19: error: 'try' without 'catch', 'finally' or resource declarations
try
^
5
You placed your try { outside the while loop, but the corresponding catch is within the while loop. But must be either outside the loop or inside the loop, together.
Try placing the try { lines inside the while loop.
Additionally, it looks like these lines won't work either:
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
All getRadius does is print out a prompt and return the passed in parameter, radius. But radius hasn't been initialized yet. But it looks like nothing is done with it yet anyway. Rename the method something like promptForRadius, and it doesn't need to take in a parameter or return anything.
public static void promptForRadius()
{
System.out.print("Enter Radius Squared Number ");
}
Then when calling it:
promptForRadius();
// Then you can call this line (unchanged)
radius = keyBoard.nextDouble();
Where your comment says // end of try it should really say // end of while and vice versa.
I have reformatted the code. Braces for try/catch block cannot end before while loop braces. Also you have to initialize variables before using them (e.g,. radius). Eclipse like IDE will be helpful to format and identify compilation errors. BTW I have not checked the logical correctness of the code but more of compilations and syntax issues
import java.util.Scanner;
public class volumeConeD
{
public static void main(String[] args)
{
Scanner keyBoard = new Scanner(System.in);// input for keyBoard
// variables
double volume;
double radius = 0.0;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{// begin of try
while (r == true)
{
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println();
System.out.println();
radius = getRadius(radius);// call to method
radius = keyBoard.nextDouble();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble();
// math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf("Volume = " + volume);
System.out.println();
System.out.print("Does the user wish to try again?");
System.out.println();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}// end of while
}// end of try
catch (Exception Error)
{
System.out.println("You entered wrong data");
}
}// end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}// end of program
This seems to be your problem
try
{
while (...)
{
int blammo;
try
{
... code
blammo = 9;
}
catch ...
{
// catching here means that the while loop will continue looping.
}
System.out.println("Blammo: " + blammo); // This results in the error: variable
// blammo might not have been initialized. This is because the assignment
// "blammo = 9" is inside the try block and if an exception was thrown before
// the assignment then it (the assignment) will never execute and blammo will
// be uninitialized.
} // end of while loop
} // end of outter try
catch ...
{
// catching here means that the exception exits the while loop.
}
You use a catch, but it's not matching with the try...
oneThird variable can be set as 1 / 3 (more precision).
Same for PI, the Math library already has a PI definition.
The function getRadius is useless, you should take it off, or maybe replace it by a function which asks the user to enter a double number.
import java.util.Scanner;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double volume, radius, height, oneThird = (1.0 / 3);
int continueExecution = 1;
try {
while (continueExecution == 1) { // same as r == true (redundant)
System.out.println("Volume of a Cone... V=1/3(3.14)r^2(h)\n\n"); // '\n' is the newline character
radius = getDoubleValue(sc, "Enter radius : ");
height = getDoubleValue(sc, "Enter height : ");
volume = oneThird * Math.PI * Math.pow(radius, 2) * height;
System.out.println("Volume = " + volume + "\nEnter 1 to start again, or another number to exit: ");
continueExecution = sc.nextInt();
}
} catch (Exception e) { // Pokemon exception handling !
System.err.println(e.getMessage());
}
}
public static double getDoubleValue(Scanner sc, String msg) {
System.out.print(msg);
return sc.nextDouble();
}