I'm frustrated with this error I'm getting on my assignment. The code I have is clearly correct and running, but I'm still getting this error that the Standard Output was not what was expected. This is the question for that particular assignment:
(Algebra: solve quadratic equations) The two roots of a quadratic equation
ax^2 + bx + c = 0 can be obtained using the following formula:
b^2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the
equation has two real roots. If it is zero, the equation has one root. If it is negative,
the equation has no real roots.
Write a program that prompts the user to enter values for a, b, and c and displays
the result based on the discriminant. If the discriminant is positive, display two
roots. If the discriminant is 0, display one root. Otherwise, display “The equation
has no real roots”.
Note that you can use Math.pow(x, 0.5) to compute 2x.
And this is my response:
import java.util.Scanner;
public class Exercise03_01 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a, b, c: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double discriminant = Math.pow(b, 2) - 4 * a * c;
if (discriminant > 0) {
double r1 = -b + Math.pow(discriminant, 0.5) / (2 * a);
double r2 = -b - Math.pow(discriminant, 0.5) / (2 * a);
System.out.println("The equation has two roots" + r1 + " and " + r2);
}
else if (discriminant == 0) {
double r1 = -b + Math.pow(discriminant, 0.5) / (2 * a);
System.out.println("The equation has one root " + r1);
}
else {
System.out.println("The equation has no real roots ");
}
}
}
Can you explain what "standard output was not what was expected" means? I this resolved as soon as possible because this assignment is due this saturday.
Thanks everyone!
I two faced such issues while submitting my assignments online. Most basic cause for which your answer was not accepted by system could be one of these :
Check for whether you need to use print or println to satisfy the conditions.
Check for decimal precisions required to match the test cases.
Check for the correctly displayed sentence(Alphabetically) to match the output.
Let us know if you found it helpful.
Related
My task is to implement the cos(x) function withou using Math. library and with the taylor polynom, my code looks like this:
public class Cosinus {
public static void main(String[] args) {
/*if(args.length == 0){
System.out.println("ERROR: Geben Sie ein Argument für x ein!");
return;
}*/
double x = 5;
double summand1 = (x*x) / 2;
double summand2 = (x*x*x*x) / (2*3*4);
double summand3 = (x*x*x*x*x*x) / (2*3*4*5*6);
double summand4 = (x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8);
double summand5 = (x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10);
double summand6 = (x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12);
double summand7 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14);
//double summand8 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16);
//double summand9 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18);
//double summand10 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20);
double cosinusFunktion = (((((((1 - summand1) + summand2) - summand3) + summand4) - summand5) + summand6) - summand7);
System.out.println(cosinusFunktion);
}
}
For x = 1, 2, 3, and 4 Y is between 1 and -1
but with x = 5 it goes too -4 and if the x are even getting bigger this continues too 1287918274.
I cant solve this task but tthe task says it is enough to implement this funktion iwth the taylor polynom and the first 11 summand. I tried this too, but then even with x = 1 the bounds are broken. How can i solve this, so x = 42.5 is in bound of -1 and 1?
Tried more summands to make the result more excact, but the bounds get broken even more.
tried implement the periodicity of x-2*PI, but I dont know where to put it and results get messed up eeven more.
you are getting an integer overflow for the factorial in the summand7 line
as a simple fix you can change the line to:
double summand7 = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / ((double) 2*3*4*5*6*7*8*9*10*11*12*13*14);
The Taylor expansion will always blow up for larger inputs. However, since:
sin(x) = sin(x + n*2*pi) // for any integer n
You can simply pre-process you input with a modulus function to prevent your output from blowing up.
I can't test compile right now, but if memory serves, you would add one of the following lines prior to computing your first summand:
x = x%(Math.PI*2)
Or, if you can't use Math
x = x%((double)3.14159265358979323846*2)
I am trying to solve a complicated mathematical expression using Java on Netbeans, however I have two problems: "cannot find symbol (variable)", and the result I get is always 'NaN'.
But when I tried 'double x = 0;' instead of 'double x;' my code works but the answer I get is always 'NaN'. I also tried initializing the variable on scan 'double x = scan.nextDouble();' but it doesn't work either.
Then I realized the pattern that most of the code I type that involves complicated math, needs to have '= 0;' for the variables to be found by the compiler.
So my real question is, what is the difference between 'double x = 0;' and 'double x;' Why does the former work in mathematical expressions, but the latter can't be detected by the compiler?
Unnecessary Information Below
//The code I made for my homework
double ans, num, den, x, y;
//double x = 0;
//double y = 0;
//variable x and y might not have been initialized
num = Math.cbrt( ((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) )) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = num / den;
System.out.print("x: ");
x = scan.nextDouble();
System.out.print("y: ");
y = scan.nextDouble();
System.out.println("\n The answer is " + ans);
I have the mathematical expression of ((\root(3)((2x^(4)y+2xy^(4)) )))/(4xy^(2x+2y))
I expect the output of
x: 2
y: 3
The answer is 0.096157...
Instead, I get the result of 'variable x and y might not have been initialized' and on another scenario I get the result of 'The answer is NaN'. I'm thinking if I can use variables for each term to solve it.
EDIT: I SUCCESSFULLY MADE THE DIVISION OF THE 'DOUBLES'
by removing the 'double x = 0;', I eliminated the possibility of
'NaN'. Instead, I declare and assign values to variables at the same time.
System.out.print("x: ");
double x = scan.nextDouble();
System.out.print("y: ");
double y = scan.nextDouble();
//preparation
//double term1, term2, term3, term4, term5, term6, exp; //x, y;
//double x = 0;
//double y = 0;
//variable x and y might not have been initialized
//double term1 = (Math.cbrt(2 * Math.pow(x,4) * y));
//double term2 = (Math.cbrt(2 * x * Math.pow(y,4)));
//double term3 = (4 * x);
//double term4 = (2 * x);
//double term5 = (2 * y);
// double exp = term4 + term5;
//double term6 = (Math.pow(y,exp));
//double num = (Math.cbrt((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y, 4))));
//double den = term3 * term6;
double num = (2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) );
double den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
double ans = Math.cbrt(num / den);
System.out.println("\n The answer is " + ans);
Local variables must be given a value before they are referred to. Since your code executes from top to bottom, the calculations will be done before x and y are initialised to the user input values. This is why it says "variable might not be initialised" in your calculations.
Your misconception might be thinking that these lines define some kind of a "relationship" between x, y, num, den:
num = Math.cbrt( ((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) )) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = num / den;
But they actually don't. They simply do the calculations, and set the variable on the left hand side to the result. However, at this point, the values of x and y are not known yet, because the x = ... and y = ... lines haven't run yet.
What if you add double x = 0 and double y = 0 at the top? That solves the compiler error. The calculation can now be carried out, but it will use the x=0 and y=0. That's all the information it has got at that moment, as the lines where you get user input has not been run yet.
What you should do is to move the lines that read the user input before the calculations:
System.out.print("x: ");
x = scan.nextDouble();
System.out.print("y: ");
y = scan.nextDouble();
num = Math.cbrt( ((2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) )) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = num / den;
System.out.println("\n The answer is " + ans);
Also, to get the expected output of 0.096157..., you need the cube root to apply to the whole fraction, not just the numerator:
num = (2 * Math.pow(x,4) * y) + (2 * x * Math.pow(y,4) );
den = (4 * x * Math.pow(y, ((2 * x) + (2 * y))));
ans = Math.cbrt(num / den);
So my real question is, what is the difference between double x = 0; and double x;
The former declares x and gives it an initial value.
The latter declares x and does not give it an initial value. You can give x a value later, but you must do this for all paths that lead to any use of the variable. For example:
double x;
if (Math.pow(2, 2) >= 0.0) {
x = 0.0;
} else {
x = 1.0;
}
System.out.println(x); // OK
versus
double x;
if (Math.pow(2, 2) >= 0.0) {
x = 0.0;
}
System.out.println(x); // ERROR
The latter is a compilation error because there is a possible path through the code where x may be used before it has been initialized.
Now anyone with highschool maths knowledge can tell you that the square of an integer will always be greater or equal to zero, and therefore the else branch will never be taken. However the Java compiler doesn't know this, and will give you a compilation error. (Indeed, it is not permitted to not give you a compilation error. I won't go into the details: they are in the JLS if you care.)
Why does the former work in mathematical expressions, but the latter can't be detected by the compiler?
Now that is an interesting question.
The answer is that = has a fundamentally different meaning in programming languages and mathematical equations.
In a programming language like Java, a = b; means "assign (set) the current value of a to the current value of b".
In an mathematical equation a = b means "for all places where these a and b variables are used, the value of a is equal to the value of b.". It is basically a constraint on the possible values of a and b.
Another way to think about this is that in mathematics, a variable in an equation represents a set of possible values. The equation constrains the set of values; e.g. a = sqrt(4) is equivalent to saying that a denotes {x | x * x == 4} which is the same as the set {-2, +2}.
Now mathematics does have cases where the notation is erroneous. For example a = a + 1 is equivalent to saying that a denotes {x | x == x + 1} ... which is the empty set.
(The notation I used above is not what classical mathematicians and formal methods people would normally use. Unfortunately, it is rather difficult to explain this unless you have taken some University level Mathematics subjects / units. Or a formal methods units in a Computer Science course.)
Finally, here are so generic Q&A's that address your other compilation and runtime errors:
What does a "Cannot find symbol" compilation error mean?
Variable might not have been initialized error
In Java, what does NaN mean?
Local variables including primitives do not have default values assigned and need to be initialized explicitly.
You have to set initial values for x and y, else the compiler protests.
Why must local variables, including primitives, always be initialized in Java?
This are other problems I ran into that is having the same issue. Can anyone point out my logic error in the following below:
Question: A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree... (Exercise 4.5)
This was my response:
import java.util.Scanner;
public class Exercise04_05 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of sides: ");
double n = input.nextDouble();
System.out.print("Enter the side: ");
double s = input.nextDouble();
double area = n * Math.pow(s, 2) / 4 * Math.tan(Math.PI / n );
System.out.println("The area of the polygon is " + area);
}
}
Please explain where the Logic error is. i commented out the code or else I'll keep getting errors preventing me from submitting the question.
Your formula is wrong and it contains an error.
First / 4 is an integer division which is rounded to an int, so you get mostly an error. You have to use / 4.0 so you get the right division.
The formula for calculation the area of a polygon is
A = 1 / 4 * n * s2 * cot(PI / n)
Note it is cotangens, not tangens. As java.math has no cotangens you have to calculate it by yourself, e.g. 1 / Math.tan(x).
So finally this should work for you:
double area = n / 4.0 * Math.pow(s, 2) / Math.tan(Math.PI / n );
I keep getting "syntax error on tokens please delete these tokens" on pretty much all of my System.out.println text after the first instance of System.out.println. I don't know what this means or how to fix it? I'm a very new beginning so there might be multiple mistakes in this code. I'm also getting "Syntax error on token ""doubled is"", invalid AssignmentOperator" and """squared is"", invalid AssignmentOperator" errors as well. This is an assignment for a class with the end result supposed to be
the opposite of n is y
n doubled is y
one-half of n is y
n squared is y
the reciprocal of n is y
one-tenth of n is y and y squared is z
n minus the last digit of n is y
the sum of n and n+1 and n+2 is y
Thank you!
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
int opposite = n*-1;
System.out.println("The opposite of" n "is" opposite);
int twoTimes = n*2;
System.out.println(n "doubled is" twoTimes);
int half = n/2;
System.out.println("half of "n "is" half);
int square= n*n;
System.out.println(n "squared is" square);
int reciprocal= 1/n;
System.out.println("the reciprocal of" n "is" reciprocal);
double fraction = n*.10;
double fractionTwo = fraction*fraction;
System.out.println("one-tenth of" n "is" fraction "and" fraction "squared is" fractionTwo);
// int lastDigit =
// System.out.println();
int sum= n+1;
int sumTwo= n+2;
int sumTotal= sum + sumTwo;
System.out.println("the sum of" n "and" sum "and" sumTwo "is" sumTotal);
}
}
**also if anybody would like to help me figure out the "n+1"/"n+2" formula and how to format that in code that would be appreciated!
There's a few mistakes with this code.
You're not concatenating correctly on any of your print to consoles.
System.out.println("The opposite of" n "is" opposite);
should be:
System.out.println("The opposite of" + n + "is" + opposite);
When we want to combine Strings we use the + sign.
int reciprocal= 1/n; will not work;
it should be double reciprocal= 1.0/n; assuming that n is an int.
"n+1"/"n+2" would simply be: double result = (n + 1.0) / (n + 2.0); assuming that n is an int.
That's not how you concatenate (link) two strings!
This code, and other similar ones,
System.out.println(n "doubled is" twoTimes);
are wrong.
I think you want to link n, "doubled is" and twoTimes together, right?
Right now you are linking them with spaces. But space characters in Java doesn't concatenate strings. So that's why the compiler complained.
In Java, + is both used to do addition and concatenation of strings! So you should change the above to:
System.out.println(n + "doubled is" + twoTimes);
But wait! Where have your spaces gone? This is because + doesn't automatically adds a space for you, you need to add it yourself.
System.out.println(n + " doubled is " + twoTimes);
Alternatively, you can use String.format to format your string. This
/* Explanation: n will be "inserted" to the first %d and twoTimes will
be inserted to the second %d. And %d basically means "express the thing in
decimal"*/
String.format("%d doubled is %d", n, twoTimes)
is the same as
n + " doubled is " + twoTimes
Regarding your formula question:
In Java, there are two different number types, int and double. (There are actually a lot more, but they're irrelevant) int and double do different things when they are divided. And they have different literals.
5 is an int literal, 5.0 is a double literal. See? Numbers without decimal places are ints and those with decimal places are called doubles.
So what's wrong with your formula? Let's first take a look at what the is the result of dividing int and double
int / int: 1 / 5 = 0
int / double: 1 / 5.0 = 0.2
double / int: 1.0 / 5 = 0.2
double / double: 1.0 / 5.0 = 0.2
int / 0: 1 / 0 = Exception!
double / 0: 1.0 / 0 = NaN
In your code:
int reciprocal= 1/n;
and other similar lines, you are doing division of int. So that's why the above code doesn't work. What you should do is change one of the numbers to a double! And also change the type to double.
double reciprocal = 1.0 / n;
------ ---
changes here as well!
Wrie a method printRoots that given 3 terms as input(a,b,c) in that order prints their roots
We have the following given information
If b²-4ac is a positive number, your program should print “The two roots are X and Y” where X is the larger root and Y is the smaller root
If b²-4ac *equals 0*, the program should print. “The equation has one X” where X is the only root
If b²-4ac is a negative number, the program should print.” The equation has two roots(-X1 + Y1i) and (-X2 and Y2i)
The term can be determined based on:
If b^2 - 4ac is a negative number, then the quadratic equation becomes: (-b+/- √C)/2a
-This means the equation can be simplified to become (-b+/- √Ci)/2a where the square root is not a positive number
Calculate the coefficient and print that(i.e X1 is -b/2a and Y1 is sqrt(-C)/2i
Note: Not allowed to use Scanners for this question
Is it possible for someone to review my program and tell me where I have gone wrong and do i just remove my scanners to make it a program without scanners?
import java.util.Scanner;//delete this part after
public class findingRoots {
public static void main(String[] args)
{
}
public static double printRoots (){ //should it be double here or int?
//read in the coefficients a,b,and c
Scanner reader = new Scanner(System.in);
int a=reader.nextInt();
System.out.println("Enter the value of a");
int b=reader.nextInt();
System.out.println("Enter the value of b");
int c=reader.nextInt();
System.out.println("Enter the value of c");
//now compte the discrimintat d
double discrimintant = d;
double X,Y; //root 1 & root 2, respectively
// is the step double X,Y necessary?
double d = (b*b)-(4.0*a*c);
if (d > 0.0){
d = Math.sqrt(d);
System.out.println("The two roots are X and Y");
double X = (-b + d)/(2.0 * a ); //X= root 1, which is larger
double Y = (-b - d)/(2.0 *a); //Y= root 2, which is the smaller root
System.out.println("Root 1" = X "and" "Root 2" "=" Y);
}
else{
if (d==0.0) //then...how to write?
System.out.println("The equation has one root X")//where X is the only root
double X = (-b + 0.0)/(2.0 * a);//repeated root
System.out.println("Root" "=" X);
}
else{
if(d < 0.0)
System.out.println("The equation has two roots (-X1 + Y1i) and (-X2 +Y2i)");
// where i represents the square root of negative 1
double X1 = -b/(2*a);
double Y1 = (Math.sqrt(-C))/(2*a);
double X2 = -b/(2*a);
double Y2 = (-(Math.sqrt(-C)))/(2*a);
double Y2 = (-(Math.sqrt(-C)))/(2*a);
System.out.println("Root 1" "=" (-X1 + Y1i) "and" "Root 2" "=" (-X2 +Y2i)");
}
}
}
you can pass input from command lines. You will get the data at args array
in public static void main(String[] args) here args refers to command line arguements
when you run a java program using
java MyApp arg1 arg2
in your main args[0] is arg1 and args[1] is arg2
So in your case run the app like following command
java findingRoots 1 2 3
and in main
int a= Integer.parseInt(args[0])
N.B I think you would like to validate the command line parameters. check both the args.length and if they are int or not