This is what I have so far. It tells me that I have a syntax error on the lines marked below, saying that it expected a "{" and a "}" respectively, without the double quotes around them. Any suggestions?
public class attempt1 {
//use Euler-Richardson algorithm
//defining the initial conditions
double v0=30;
double theta=40;
double x0=0;
double y0=0;
double v0x=v0*Math.cos(Math.toRadians(theta));
double v0y=v0*Math.sin(Math.toRadians(theta));
double dt= .01;
double ax=0;
double ay=-9.8;
double x=0;
double y=0; //this line here, on the semi-colon
while (y>=0) {
double vx= v0x+1/2*ax*dt;
double vy= v0y+1/2*ay*dt;
double x= x0+1/2*vx*dt;
double y= y0+1/2*vy*dt;
if (y<=0){System.out.println(x);}
}
} //and right over here, on the brace itself
You are trying to run statements inside a class body. They should be in a method. like this:
public class Attempt1{
private void doSomething(){
//example code
int a = 1 + 1;
while (a < 2) {
//do random stuff
}
}
}
Right now you have something similar to this:
public class Attempt1 {
//while{...} <---- WRONG!
}
Statements should be in a method (sometimes called function) at all times.
You can however put variables outside a method. This will make them accessible for all methods in that class.
You should check out some starting tutorials like the one Oracle gives:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/
Related
I'm trying to write a java program that will solve any ordinary differential equations using Euler method, but I don't know how to write a code to get any differential equation from the user. I was only able to write the code to solve a predefined ordinary differential equations.
I was able to come with a code to solve some particular ordinary differential equations which were written as functions in the program, I also made research online to look for similar problems but it seem they also wrote it to solve some designated problem not general questions on ordinary differential equations. This was found in most of the article have read online.
Here is my Euler class;
import java.lang.Math;
public class Euler {
private double x0, y0, x1, y1, h, actual;
public Euler (double initialx, double initialy,double stepsize,double finalx1) {
x0 = initialx; y0 = initialy; h=stepsize; x1 = finalx1;
}
public void setEuler (double initialx, double initialy,double stepsize,
double finalx1){
x0 = initialx;y0 = initialy;h =stepsize;x1 = finalx1;
}
public double getinitialx(){
return x0;
}
public double getinitialy(){
return y0;
}
public double getinitialexact(){
return (double) (0.9048*Math.exp(0.1*x0*x0));
}
double func(double x, double y){
return (double) (0.2*x*y);
}
double funct(double x){
return (double) (java.lang.Math.exp(0.1*x*x));
}
public double getinitialerror(){
return (double) Math.abs(actual - y0);
}
public double getEulerResult(){
for (double i = x0 + h; i < x1; i += h){
y0 = y0 + h *(func(x0,y0));
x0 += h;
double actual = (0.9048*funct(x0));
double error = Math.abs(actual - y0);
System.out.printf("%f\t%f\t%f\t%f\n",x0,y0,actual, error);
}
return y0;
}
}
Here is my Driver's class
import java.util.Scanner;
public class EulerTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Euler myEuler = new Euler(1.0,1.0,0.1,1.5);
System.out.println( "x\t explicit\tactual\t error\t " );
System.out.printf("%f\t%f\t%f\t%f\n", myEuler.getinitialx(),
myEuler.getinitialy(),myEuler.getinitialexact(),
myEuler.getinitialerror());
System.out.printf("my approximated value is %f\n\n",
myEuler.getEulerResult ());
System.out.println("enter another initial value of x: ");
double initialx = input.nextDouble();
System.out.println("enter another initial value of y: ");
double initialy = input.nextDouble();
System.out.println("enter another stepsize value of h: ");
double stepsize = input.nextDouble();
System.out.println("enter another upper bound of x: ");
double finalx1 = input.nextDouble();
myEuler.setEuler(initialx,initialy,stepsize,finalx1);
System.out.println( "x\t explicit\tactual\t error\t " );
System.out.printf("%f\t%f\t%f\t%f\n", myEuler.getinitialx(),
myEuler.getinitialy(),myEuler.getinitialexact(),
myEuler.getinitialerror());
System.out.printf("my approximated value is %f\n\n",
myEuler.getEulerResult ());
}
}
I will be glad if i can en lighted on how to write the java code to collect any ordinary differential equation from the user so as to solve using Euler's method.
What you are looking for is the ability to compile some code at run time, where part of the code is supplied by the user.
There is a package called JOOR that gives you a Reflect class that contains a compile method. The method takes two parameters (a package name:String and the Java code:String).
I've never personally used it, so can not vouch for its robustness, but here is a tutorial and the javadoc:
https://www.jooq.org/products/jOOR/javadoc/latest/org.jooq.joor/org/joor/Reflect.html#compile(java.lang.String,java.lang.String)
https://blog.jooq.org/2018/04/03/how-to-compile-a-class-at-runtime-with-java-8-and-9/
In your case, you would put your user supplied function in place of the following line of code:
return \"Hello World!\";\n"
Beware, you need to be 100% absolutely unconditionally guaranteed that the user can only ever enter a function to be solved. If they are supplying code, remember that unless you take safeguards, the code they enter could very easily be code the removes all of the files on your hard drive (or worse).
For the second part of your question - how do i implement a solution in Java using Euler's method, perhaps check out this link: Euler's Method in java or this https://rosettacode.org/wiki/Euler_method#Java which has it in pretty much every language you can imagine (and probably some you can't).
I am new to using java and am having some issues in my java class right now and will be needing help with my specific code. I try to look at others questions on here all the time but it's never exactly what I need. Here are my directions:
Create a Java file called CompoundInterestYourLastName. Write a method called computeBalance() that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
Use a loop to control the iterations through the years in your method.
Your method should return a double value.
In your main method, run the following tests to verify your method is working correctly.
System.out.printf("Your total is $%.2f", computeBalance(1000, .045, 3));
// should return $1141.17
I am using eclipse and my only current error is in the comments. I also want some general tips and let me know if my logic is wrong. It probably is. :D
Here is what I have currently although I have been trying different things:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestTidwell {
public static void main(String[] args) {
double compInt = computeBalance(1000, 0.045, 3);
System.out.printf("Your new balance is $%.2f", compInt);
}
// Getting arror for line of code below.
// Error: This method must return a result of type double
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
double compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
return compInt;
}
}
}
}
Thanks.
Your function computeBalance doesn't guarantee to return a value, because the only return statement is in an if clause, within a loop (making it two conditions deep).
This is a thing the compiler is warning you about. Basically it scans your code and makes sure that a function declared as double will actually return a valid value of type double and so on.
If you add a return statement at the end of the body in the function (or throw an error) it should compile.
I am not exactly sure what your function does in technical terms, but I've rewritten it so it should return the same value, but should now actually compile.
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
double compInt = 0; // Declare compInt outside the loop.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
break; // Break instead of return, will immediately
// go to the return statement outside the loop.
}
}
return compInt; // Moved the return statement to outside the loop so
// the function always will return a double.
}
The error I'm getting is:
"Cannot invoke yearlyPay() on the primitive type double"
I'm trying to call the method: yearlyPay() on the variable calcPay.
I've created yearlyPay() and it looks as so:
public double yearlyPay(double pay)
{
double yearlyPay = hourlyRate * HOURS_YEAR;
System.out.println("public double yearlyPay(double pay): " + yearlyPay);
System.out.println("");
return yearlyPay;
}
then I have another method where calcPay is located
public double localTax(double calcPay)
{
double pay = calcPay;
double localTax;
if (pay.yearlyPay() < 45000)
{
localTax = (1.15 / 100) * pay;
}
else
localTax = (1.15 / 100) * 45000;
return localTax;
}
I also figured that having
double pay = calcPay
is kinda redundant, so I changed it to
public double localTax(double calcPay)
{ //removed double pay = calcPay
double localTax;
if (calcPay.yearlyPay() < 45000)
{
localTax = (1.15 / 100) * pay;
}
else
localTax = (1.15 / 100) * 45000;
return localTax;
}
But...same thing happened.
I googled the problem (with the error message) but I didn't find anything that helped.
There was a place that said to change double to Double, but I didn't know which ones where to change. So I tried each one, one by one...needless to say that didn't work either.
Any help would be appreciated. There is more to the code (which is homework). I didn't post it all cuz I don't think it's useful. Ask if you need specific though.
Also if this question is similar to this one, let me know, I'll delete this and look at that one. I probably missed it in the 3,000,000+ search results on google.
Only objects have methods.
A double is a primitive not an object.
Your yearlyPay() method is a method of the class you are writing, not of double.
So if yearlyPay() is defined in the same class as the call, you call it as:
double n = yearlyPay(calcPay);
... or if you wrote the method in another class (say, PayCalculator):
PayCalculator payCalculator = new PayCalculator();
...
double n = payCalculator.yearlyPay(calcPay);
... or if the method is in PayCalculator as a static method:
double n = PayCalculator.yearlyPay(calcPay);
Incidentally, it's not a good idea to use floating-point number types for money calculations. Google for reasons.
I need to use information gathered from my main method in a different method within the same class. Is that possible? If so, how do I go about doing so? Basically I have to gather the info in main method and implement it in the other. Help!
If I gain information say:
import java.util.Scanner;
public class MyClass
{
public static double main (String[] args)
{
double x, y, z;
Scanner scan = new Scanner(System.in);
System.out.print ("Please enter x value: ");
x= scan.nextDouble();
System.out.print ("Please enter y value: ");
y= scan.nextDouble();
System.out.print ("Please enter z value: ");
z= scan.nextDouble();
}
public static void OtherMethod()
{
int a=0;
while(x<y)
{
a++;
double b=x* (z/100);
x+=b;
}
System.out.println("After " + a + " time at " + z+ "%, you will have " + "$" + x);
}
}
It sounds like you are asking how to pass arguments to a function.
Try writing:
public static void OtherMethod(double x, double y, double z)
Inside Main:
OtherMethod(x,y,z)
Yes. If you change the first line of OtherMethod to
public static void OtherMethod(double x, double y, double z)
then you can call it from main with
OtherMethod(x, y, z);
which makes the x, y, z defined in OtherMethod equal to the x, y, z defined in main, for the purposes of the one method call.
Gratuitous advice
For the record, there are a few bad programming practices in your code snippet. It's OK for now, since you're a beginner, but don't make a habit of any of them.
Single letter variable names. It's not obvious to someone working on this code that x is an amount of money, y is your savings target, z is the interest rate, and so on. You should use full words or even multiple words for your variables. Like savingsTarget and interestRate.
Inconsistent spacing and indentation make code hard to read.
Most people prefer not to put the { character on a line by itself. Put it at the end of the previous line instead.
You've used floating point types for money. Don't ever store an amount of money in a double or a float variable. These aren't designed for accurate mathematics with decimals. Learn to use the BigDecimal class instead.
Having static methods instead of creating objects is often indicative of poor design. It also makes big programs much more difficult to test, if there are many static methods.
Method names should begin with a lower case letter. It makes your code a little easier to follow.
Just a few things to think about for your future programming efforts.
declare double x, y, z; as class level static attibutes -
private static double x;
private static double y;
private static double z;
Inside your main method then you can call OtherMethod();
I did the problem but I only found out How to do it for one value of x? Here is the program.
public class PointsOnACircleV1 {
public static void main(String[ ] args)
{
double r = 1;
double x = 0.1;
double equation1= Math.pow(r,2);
double equation2= Math.pow(x,2);
double y = Math.sqrt(equation1-equation2);
System.out.println(y);
}
}
I got the correct answer .99 (......)
I need mine to show multiple values of x. Here is how the output should be. Please help if you can.
Use a for loop.
Related Documentation
The for statement.
In order to get it to print multiple values you first need to fill the "String [] args" but you need to ahve them as double to be able to multiply them with other values. In your case that's the X-values, so lets say over the code you posted
public class PointsOnACircleV1 {
//initialize your array with your values
double [ ] args = { 1.0, 0.9, 0.8,.... and so on until you reach 0.1, 0.0};
//you could fill it other more effective ways but just to show you!
public static void main(double[ ] args)
{
double r = 1;
// no need to fill this as you already done
// it double x = 0.1;
for(Iterator<double> i = args.iterator(); args.hasNext(); )
{
//this is the number you want to multiply with
double numbertomultiply = args.next();
double equation1= Math.pow(r,2);
double equation2= Math.pow(numbertomultiply,2);
double y = Math.sqrt(equation1-equation2);
System.out.println(y);
}
}
Just written from my head havent checked it but just to give you a sample :)
EDIT Use the other answers to initialize your array.