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.
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;
}
}
}
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();
Currently I am creating (trying) a program for Newton's Method and its suppose to allow you to guess the initial root and give you the roots. But I can't figure out how to put the
x1=x0-f(x0)/f(x0) also needs a loop
Here's my code currently :
import java.util.Scanner;
public class NewtonsMethod {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your guess for the root:");
double x = keyboard.nextDouble();
double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
for(x=x-f(x)/f(x));
System.out.println("Your answer is:" + guessRootAnswer);
}
}
You've misstated how newton's method works:
The correct formula is:
xn+1 <= xn-f(xn)/f '(xn)
Note that the second function is the first order derivative of the first one.
How the first order derivative looks depends on the exact nature of the function.
If you know what f(x) looks like, when you code the program, you can also fill in the code for the first derivative. If you have to figure it out at runtime, it looks like much more or a massive undertaking.
The following code from: http://www.ugrad.math.ubc.ca/Flat/newton-code.html
demonstrates the concept:
class Newton {
//our functio f(x)
static double f(double x) {
return Math.sin(x);
}
//f'(x) /*first derivative*/
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Stop if you're close enough
int max_count = 200; // Maximum number of Newton's method iterations
/* x is our current guess. If no command line guess is given,
we take 0 as our starting point. */
double x = 0;
if(argv.length==1) {
x= Double.valueOf(argv[0]).doubleValue();
}
for( int count=1;
//Carry on till we're close, or we've run it 200 times.
(Math.abs(f(x)) > tolerance) && ( count < max_count);
count ++) {
x= x - f(x)/fprime(x); //Newtons method.
System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
}
//OK, done let's report on the outcomes.
if( Math.abs(f(x)) <= tolerance) {
System.out.println("Zero found at x="+x);
} else {
System.out.println("Failed to find a zero");
}
}
}
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.
I must be failing to wrap my head around the concept of trying to store a value in a recursive method. Solving this using iteration would take seconds, but I am struggling with the recursive call. Basically I am trying to solve: 1/1 + 1/2 + 1/3 ...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter in the end number for the sequence: ");
int endpoint = input.nextInt();
System.out.println("The value of the sequence is : " + calcSequence(endpoint));
}
public static double calcSequence (int index){
if (index == 0)
return 0;
else
return (1/index) + calcSequence(index - 1);
}
You need to add some explicit type conversions. Your 1/index is being performed as integer division, and your call is losing all its precision. Simply changing this to 1.0/index (or 1d/index to indicate that the 1 should be used as a double) should get you what you're looking for.