I have a main method and 4 other function type methods which include calculations, however, How would I call each one up into the main and proceed to print out the calculations. Also I am currently getting a lot of syntax errors.
I've tried placing brackets and braces when needed, however, that has just resulted into more errors. Also, I tried initializing Strings and integers elsewhere, which still seems to fail to work. Any help would be much appreciated!
Some syntax errors include: ';' expected on line 60
insert ';' to complete localVariableDelcartion on line 60
these errors are repeated for every line
import java.io.*;
//create the class
public class CirclemethodsFixedagain
{
//main method
public static void main(String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
// more user questions
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
System.out.println("*NOTE* Pressing a key outside of this range or a regular character will re-prompt the original message");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
// more user questions
System.out.println("Now enter the radius of the required shape(Half of diameter)");
System.out.println("*NOTE* Pressing a regular character will re-prompt the original message");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
}
//user created method, with each
public static int circlemethods(double circumference) throws IOException {
{
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
circumference = (Math.PI) * (2) * (num);
System.out.print("The circumference of that sphere is :");
return circumference;
}
public static double circlemethods2 (double area) throws IOException
{
if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
area = (Math.PI * num * num);
System.out.print("The area of the circle is :");
return area;
}
}
public static double circlemethods3 (double volume) throws IOException
{
if (numInput == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
volume = (4 * Math.PI * num * num * num) / 3 ;
System.out.print("The volume of that sphere is : cm³");
return volume;
}
}
public static double circlemethods4 (double surfaceArea) throws IOException
if (numInput == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
surfaceArea = 4 * Math.PI * num * num;
System.out.print("The Surface area of that sphere is :");
return surfaceArea;
}
}
}
}
Your braces - the { and } characters - don't match up. I have fixed the indentation of the code in the question so that you can better see where the problem gets started - in the method circlemethods. Also, circlemethods4 is missing its braces.
Keeping consistent indentation levels throughout the program makes these kinds of errors a lot more obvious to spot.
Compilation errors are caused by:
You can not place methods inside other method, move circlemethods 2,3,4 outside the circlemethod1.
Your circlemethods don't see numInt local variable. It is declared in main method and it is visible only in that one.
I believe you don't need if statements at the begining of each circlemethods. You rather need something like that:
if (numInt == 1)
{
circlemethod1(radius);
} else if (numInt == 2) {
circlemethod2(radius);
}
etc. in your main method.
You can also change argument's name of each circlemethod, as I understood it is always radius. Current name of arguments is a good candidate for method name.
Following are the inputs that will fix the problem :
You can't declare method inside a method, It's not JAVA syntax. Just check the bracing correctly. Use any IDE for doing the same.
Make numInt, num as static (Class) variables. As you are using those in static method.
Use proper names and camelCasing nomenclature to name any method.
|e.g calculateCircleArea(), calculateCircleVolume(), etc..
Hope this solves your problem.
Related
I finally got my program to compile without any errors and the first half is correct the total pay, retirement deduction and net pay were all displaying 0. I saw from a different post that Java doesn't analyze the logic of your if blocks so I edited my code to have my rate assigned to 0 and my if statement to return rate. I'm now getting the error "unexpected return value". How do I get my program to have the appropriate value depending on the user's input?
import java.util.*;
public class AcmePay {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
double hours;
int shift;
int plan;
double rate = 0;
double overtimePay;
double paycheck;
//double retirement;
// double retirement = paycheck - (paycheck * .03);
//double netPay = paycheck - retirement;
System.out.println("How many hours did you work this week?");
hours = keyboard.nextDouble();
if ( hours <= 40 )
{
paycheck = hours * rate;
}
else
{
paycheck = (40 * rate) + ((hours - 40)) * (rate*1.5);
}
System.out.println("What shift did you work? 1, 2, or 3?");
shift = keyboard.nextInt();
if (shift == 1)
{
rate = 17;
return rate;
}
else if (shift == 2)
{
rate = 18.50;
return rate;
}
else if (shift == 3)
{
rate = 22;
return rate;
}
To print the rate, the last part of your code can be like this:
shift = keyboard.nextInt();
if (shift == 1) {
rate = 17;
} else if (shift == 2) {
rate = 18.50;
} else if (shift == 3) {
rate = 22;
}
System.out.println("Rate = " + rate);
i.e. remove the return statements and then print the rate at the end. You can't return a value from a void method like main(), hence the error.
If you want to calculate the rate using a separate method, you would do something like this:
private static double rateForShift(int shift) {
if (shift == 1) {
return 17;
} else if (shift == 2) {
return 18.50;
} else if (shift == 3) {
return 22;
}
return 0;
}
This method returns a double, so now you can (and have to) use return statements.
You would call it from the main method with:
double rate = rateForShift(shift);
It's a good idea to split your code into focused methods, like this, because it makes it easier to read and work with.
I think your code has a "logic" bug in it because you are using the rate variable to calclulate paycheck, but the rate variable is always 0 at the point you use it. You should probably ask both questions before you calculate the paycheck amount.
A full program would look like this:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many hours did you work this week?");
double hours = keyboard.nextDouble();
System.out.println("What shift did you work? 1, 2, or 3?");
int shift = keyboard.nextInt();
double paycheck = calculatePayCheck(rateForShift(shift), hours);
System.out.println("Paycheck = $" + paycheck);
}
private static double calculatePayCheck(double rate, double hours) {
if (hours <= 40) {
return hours * rate;
} else {
return (40 * rate) + ((hours - 40) * (rate * 1.5));
}
}
private static double rateForShift(int shift) {
if (shift == 1) {
return 17;
} else if (shift == 2) {
return 18.50;
} else if (shift == 3) {
return 22;
}
return 0;
}
In Java programs you don't need to declare your variables at the top. The convention is to declare them as you need them.
Example
How many hours did you work this week?
20
What shift did you work? 1, 2, or 3?
2
Paycheck = $370.0
It's also worth mentioning that, although fine for a toy example, in a real system you should not use floating point numbers (like double) to represent money.
ELEVATE covered the code, so I'll cover the theory.
In Java (and in many other programming languages), a method is a block of code that may or may not take in an input and may or may not give an output. Whether or not the method gives an output can be determined by analyzing the method definition. If a primitive type (for example, int or double) or Object (for example, Scanner) is used in the method definition, then that method will return that type as output. If the keyword void is used in the method definition, then that method will return no output.
A key point to understand is this: Once a method is told to return a value, that method will terminate. Thus, you cannot include any code after a return statement, or your compiler will be angry with you and yell at you for including "unreachable code."
Now, to apply this to the specifics. The main method in Java uses the keyword void to indicate that it will not return any sort of output. Thus, return rate; is inappropriate for two reasons:
Returning a double value is indeed some sort of output, which contradicts the method definition of main in which main was set to return no output by the keyword void.
return rate; will cause your program to terminate immediately. Assuming that ELEVATE was correct about how you should reorder your code, leaving a return statement in your answer would cause you further problems by preventing your code from moving on to calculate your paycheck.
Side Note: A method that returns no output can still use the return keyword, but it cannot be used with any sort of value or object. For example, the following method is valid because return isn't paired with any sort of value.
public class ReturnExample {
/*Other stuff.*/
public void returnNothing() {
System.out.println("Now returning nothing.");
return;
}
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm working on a program that calculates the area of either a circle (C), square (S), or rectangle (R), depending on what letter the user inputs. I've tested it and it works fine; the code is below:
import java.util.Scanner;
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
String Shape = input.nextLine();
if (Shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
}
else if (Shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
}
else if (Shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
}
Now, what I want to do is add a loop to the program. For example, if the user inputs C for circle and puts in the number 22 for the radius, they'll get an answer, but I want the program to loop back to the beginning again so that it asks the user "What is your shape?...". Also, if the user types in X instead of C, S, or R, I want the program to quit, but I'm not sure how to add that in, either.
I know that I need to add a 'while' loop, but I was hoping someone could point me in the right direction, because I don't know where to insert that part of the code. Do I add the 'while' loop somewhere at the beginning of the code, after the last "if else" statement, or... Also, I'm not actually sure what to type. Should it be something like,
while (Shape == C, S, R) {
....?
Any help or pointers would be appreciated by any one in the coding community! I will continue to work on this code on my own as well.
I would go for the do, while
So, the program will always do something while the conditions that are set are being accomplished, so you want your program to look something like:
public class TestLoops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean thisB = false; /*this is the guy who will tell the loop to stop the execution when the user inserts X*/
String shape;
do{
System.out.println("What is your shape? Enter C for circle, S for " +
"square, R for rectangle, or X to exit: ");
shape = input.next();
if(shape.equalsIgnoreCase("C") || shape.equalsIgnoreCase("S") || shape.equalsIgnoreCase("R")) {
if (shape.equals("C")) {
System.out.println("What is your circle's radius?: ");
double Radius = input.nextDouble();
double cFormula = (3.14 * Radius * Radius);
System.out.println("Your circle's area = " + cFormula);
} else if (shape.equals("S")) {
System.out.println("What is the length of your shape's sides?: ");
double Side = input.nextDouble();
double sFormula = (Side * Side);
System.out.println("Your square's area = " + sFormula);
} else if (shape.equals("R")) {
System.out.println("What is your rectangle's height?: ");
double Height = input.nextDouble();
System.out.println("What is your rectangle's width?: ");
double Width = input.nextDouble();
double rFormula = (Height * Width);
System.out.println("Your rectangle's area = " + rFormula);
}
}
else if (shape.equalsIgnoreCase("X")) thisB = true;/*or in other words: stop*/
}
while(!thisB);
}
}
Things to consider:
1) Naming conventions, always start variable names with undercase using camelCase, in your example shape started with UpperCase
2) When in a while loop, use only next(), not nextLine() to pick up the values as the latter will duplicate the question in the System.out.Println.
3) The optimum way to do this is to put all your if clauses in a method and call it with the parameter from the Scanner input. Even better would be having a method per shape, as things can get hairy depending on requests
Okay so I have a homework assignment and I'm having difficulty calling a method on my main class that is in another class.
Basically the "test" method is in the landEnclosure.java class and I'm trying to call it on my main class which is landAndEat.java
They're both inside the same package:
Image
This is the main class where I'm trying to call the method:
public class landAndEat {
public static void main(String[] args) {
test();
} //end class
} //end main
This is the class where the method is being created:
import java.util.Scanner;
public class landEnclosure {
public void test() {
double area, ratioA = 0, ratioB = 0, x, l, w, perimeter;
Scanner input = new Scanner(System.in);
System.out.println("What area do you need for your enclosure in square feet?");
area = input.nextDouble();
if( area > 0 && area <= 1000000000) { //Input specification 1
System.out.println("What is the ratio of the length to the width of your enclosure?");
ratioA = input.nextDouble();
ratioB = input.nextDouble();
}
else
System.out.println("It needs to be a positive number less than or equal to 1,000,000,000!");
if(ratioA > 0 && ratioA < 100 && ratioB > 0 && ratioB < 100) { //Input specification 2
x = Math.sqrt(area/(ratioA*ratioB));
l = ratioA * x;
w = ratioB * x;
perimeter = (2 * l) + (2* w);
System.out.println("Your enclosure has dimensions");
System.out.printf("%.2f feet by %.2f feet.\n", l, w);
System.out.println("You will need " + perimeter + " feet of fence total");
}
else
System.out.println("The ratio needs to be a positive number!");
}
} //end class
In java the only top level "things" are classes (and similar stuff such as interfaces and enums). Functions are not top level "things". They can exist only inside a class. Thus to call it you need to go through that class, or through an object of that class.
From the code you have written it seems that test is a non static method. In that case you need to create an object from that class, and run the method on it :
landEnclosure l = new landEnclosure();
l.test();
However, it seems that your intention is for 'test' to be a static method. In that case, declare it static and call it that way :
landEnclosure.test();
On a side note, the convention in Java is to name classes with an upper case first :
class LandEnclosure {
Besides the obvious suggestions of creating a new instance of landEnclosure, you can also make the function static and call:
landEnclosure.test();
Ok, I'm a beginner in java, learning on my own through websites and books. I tried a simple square root calculator with a for loop and a while loop (I've included what I tried below). Sadly, all my code does when I enter a number is terminate. Any help would be appreciated!
import java.util.Scanner;
public class The2RootProdject {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double rootIt = input.nextDouble();
double dummy = 0.0000000;
while (dummy != dummy * dummy) {
dummy += 0.0000001;
if (rootIt == dummy * dummy) {
System.out.println("the squar root of " + rootIt + " is "
+ (dummy * dummy));
}
}
}
}
You have a couple of problems here:
1) Logical bug: 0 == 0 * 0
<= This means while (dummy != dummy * dummy) {..} will never be untrue, and you'll never even enter the loop
2) Floating point numbers are inexact, so your algorithm (which relies on "==") might not work anyway
Look here for more details on floating point imprecision:
http://www.lahey.com/float.htm
This is true for ANY language - your algorithm for square root must take this into account.
Try to use this algorithm which use Newton's iteration:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
double number, t, squareRoot;
Scanner input = new Scanner(System.in);
number = input.nextDouble();
squareRoot = number / 2;
do
{
t = squareRoot;
squareRoot = (t + (number / t)) / 2;
}
while ((t - squareRoot) != 0);
System.out.println(squareRoot);
}
}
Newton's iteration is an algorithm for computing the square root of a number via the recurrence equation:
X(n+1) = (X(n) + number/X(n))/2
I think the while condition is supposed to be =
while(rootIt != dummy * dummy) {}
Your current condition will only ever be true if you initialized dummy as 1; but I don't that would be what you want anyways.
Responses to previous question , my initial answer to that question had been solved, but I had another problem when it came down to looping which was later solved by simply using a for loop.
However, my problem is I do not want the user to constantly have to restart the program after an exception is handled, rather I want it to loop the same beginning questions to the user. I've tried placing print statements after the return statements, and also tried completely copying the logic code after the try catch, however, realizing that that would not cause the user to loop unlimited times for the exception. Also, on a side note yes my previous question had good answers, however, no one managed to answer my more recurring problem, which is why no one got the check mark towards their answer.
import java.io.*;
import java.text.DecimalFormat;
public class Test
{
public static void main(String[] args) throws IOException
{
double x;
x = circlemethods(0.0, 0.0, 0.0, 1.0);
}
public static double circlemethods(double volume, double surfacearea,
double area, double radius) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
double answer = 0;
double amount = 0;
double answer2 = 0;
double answer3 = 0;
double answer4 = 0;
for (double i = 0; i < 999; i++)
;
try
{
// for (double i = 0; i < 999; i++);
// while (numInt != 999) {
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
System.out.println("Now enter the radius of the required shape(Half of diameter)");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
DecimalFormat nextAmount = new DecimalFormat("0.00");
amountStr = nextAmount.format(amount);
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
answer = (3.14) * (2) * (num);
System.out.print("The circumference of that sphere is :");
System.out.println(answer + "cm³");
return answer;
}
else if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
answer2 = (3.14) * 2;
System.out.print("The area of the circle is :");
System.out.println(answer2 + "cm²");
return answer2;
}
else if (numInt == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
answer3 = 4 / 3 * (3.14) * (num) * (3) * (3) * (3);
System.out.print("The volume of that sphere is : cm³");
System.out.println(answer3 + "cm³");
return answer3;
}
else
// if (numInt == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
answer4 = 4 * (3.14) * (num) * (2) * (2);
System.out.print("The Surface area of that sphere is :");
System.out.println(answer4 + "cm²");
return answer4;
}
} catch (Exception e)
{
System.out.println("Please do not enter any string values, next time input enter a number ");
return 0;
// how to loop this untill the user inputs a number????
}
}
}
First, you use a while(true) loop instead of looping for 999 times. (That loop doesn't actually do anything considering there is a semicolon right after it.)
Then, you remove the return 0; from your catch block.
So it would be
while(true) {
try {
.... //your code
}
catch {...}
} //while loop end bracket
This way, the loop will only end if it reaches one of your return statements.
You need to loop until you get a valid value. One way to do that is loop until a boolean value is set to true. Try something similar to this:
boolean inputIsValid = false;
while (!inputIsValid) { ...
Then when you have determined you have a valid input, add the line:
inputIsValid = true;
Your loop will continue until inputIsValid becomes true.
You could also create an endless while loop. Then when you receive a valid input, break out of the loop:
while(true) {
//when valid input is received
break;
}