Correcting a formula in java - java

My first assignment requires me to write a program that expresses a formula. The formula as written in the assignment :
y = 4x^3 + 8x^2 - 31x - 35 / (3x2 + 1)^1/2 + 2 * | x - 1.5 |
| means absolute value; (...)1/2 means square root
Also how should I create a code that prints how many times the formula prints out a positive or negative number or zero?
Here is how I created my assignment's program:
import java.io.*;
public class hw1 {
public static void main(String[] args) throws IOException
{
System.out.println("My name is Jibran Khan and this is the output of my first program.");
double x; double y;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50)
{
y=((4*(x*x*x))) + (8*(x*x))-(31*x)-35/Math.sqrt(3*x*x+1)+2* Math.abs(x-1.5);
System.out.println("X = " + x + "Y = " + y );
if (y<=0.0) System.out.println("Y is negative");
if (y>=0.0) System.out.println("Y is positive");
if (y == 0.0) System.out.println("Y is zero");
}
System.out.println();
System.out.println("My first program is complete");
outFile.close();
}
}

OK, you want to make a test on a simple math formula. You have to test the results and define how many results are positive, negative or equal to 0 ...
You have to update your tests... It result is equal to 0, your test returns positive, negative and null results.
You also have to count results. So implement counters for each type of results and increment them in the if statement.
public static void main(String[] args) throws IOException {
double x; double y;
int positive = 0;
int negative = 0;
int equalZero = 0;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50) {
y = Math.pow(4,3) + ... ( your formula)
System.out.println("X = " + x + "Y = " + y );
if (y < 0.0) {
System.out.println("Y is negative");
negative++;
} else if (y > 0.0) {
System.out.println("Y is positive");
positive++;
} else {
System.out.println("Y is zero");
equalZero++;
}
}
System.out.println();
System.out.println("Positive results : " + positive);
System.out.println("Negative results : " + negative);
System.out.println("Equal to zero : " + equalZero);
outFile.close();
}

Calculate the Denominator and Numerator in different variables, that will give more readability and you will be able to spot the mistakes easily.
Also, the conditions you gave for y: (y <= 0.0) and (y >= 0.0) will be true for zero so the last condition y == 0.0 is not reachable.

Related

Solving mismatch exceptions only appearing in one compiler

This is for an online assignment. The goal is to accept two inputs (in this code, the x and y variables) multiple times and then print the largest and smallest value of each variable. Here is the code:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
class Lesson_20_Activity_One{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
double x; //the latitude input
double y; //the longitude input
double n = -90; //the maximum north value
double e = -180; //the maximum east value
double s = 90; //the maximum south value
double w = 180; //the maximum west value
int escape = 1; //the value that dictates when it's time to exit the while loop
while (escape == 1) {
System.out.println("Please enter the latitude:");
x = scan.nextDouble();
System.out.println("Please enter the longitude:");
y = scan.nextDouble();
if ((x>n) && (x<=90))
n = x;
if ((x<s) && (x>=-90))
s = x;
if ((y>e) && (y<=180))
e = y;
if ((y<w) && (y>=-180))
w = y;
if ((x>90)||(x<-90)||(y>180)||(y<-180))
System.out.println("Incorrect Latitude or Longitude");
System.out.println("Would you like to enter another location?");
escape = scan.nextInt();
}
System.out.println("Farthest North: " + n);
System.out.println("Farthest South: " + s);
System.out.println("Farthest East: " + e);
System.out.println("Farthest West: " + w);
}
}
This code runs exactly as intended on my personal compiler, Eclipse. However, when running this same program on the course's online compiler, I am met with these errors:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Lesson_20_Activity.main(Main.java:322)
at Ideone.assertRegex(Main.java:85)
at Ideone.assertRegex(Main.java:76)
at Ideone.test(Main.java:40)
at Ideone.main(Main.java:29)
What can I do to solve these errors? It seems it's a problem with my Scanner, but I don't know how to fix it.
The error trace seems to indicate that the InputMismatchException is thrown when scan.nextInt() is called.
After your print System.out.println("Would you like to enter another location?");, if the user inputs anything other than an integer, scan.nextInt() will throw an exception. Even if you read the user's input as a string as suggested by someone else, the parseInt method in escape = Integer.parseInt(scan.nextLine()) will throw an error because the string may not be a valid integer.
I suggest adding try-catch block as follows around the scan.nextInt() call so that your program doesn't crash when a user inputs something other than a valid integer (like the number 8.238).
boolean inputValid = false;
System.out.println("Would you like to enter another location?");
while (!inputValid) {
try {
escape = scan.nextInt();
inputValid = true;
} catch (InputMismatchException e) {
inputValid = false;
System.out.println("Please enter a valid Integer");
}
}
This code will continue asking the user until the user enters a valid integer.
It might be because the online scanner's implementation of nextInt() is different and is causing the problems.
Perhaps trying to parse the input as a string and the as a double/int would work:
Scanner scan = new Scanner(System.in);
double x; // the latitude input
double y; // the longitude input
double n = -90; // the maximum north value
double e = -180; // the maximum east value
double s = 90; // the maximum south value
double w = 180; // the maximum west value
int escape = 1; // the value that dictates when it's time to exit the
// while loop
while (escape == 1) {
System.out.println("Please enter the latitude:");
x = Double.parseDouble(scan.nextLine());
System.out.println("Please enter the longitude:");
y = Double.parseDouble(scan.nextLine());
if ((x > n) && (x <= 90))
n = x;
if ((x < s) && (x >= -90))
s = x;
if ((y > e) && (y <= 180))
e = y;
if ((y < w) && (y >= -180))
w = y;
if ((x > 90) || (x < -90) || (y > 180) || (y < -180))
System.out.println("Incorrect Latitude or Longitude");
System.out.println("Would you like to enter another location?");
escape = Integer.parseInt(scan.nextLine());
}
System.out.println("Farthest North: " + n);
System.out.println("Farthest South: " + s);
System.out.println("Farthest East: " + e);
System.out.println("Farthest West: " + w);
Again, this depends on the online scanner's way of doing things.

quadratic equation solver fails to get result in Java

I have code that is supposed to solve a quadratic equation but yields NaN as a result.
I've looked around for 2 days now and I can't find a solution. Any and all advice will be more than appreciated!
package quadratic;
import java.util.Scanner;
public class Formlua {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter value of A ");
double a = input.nextDouble();
System.out.println("enter value of B ");
double b = input.nextDouble();
System.out.println("enter value of C ");
double c = input.nextDouble();
double four = 4;
double square = Math.sqrt(b* b - 4 * a * c );
double root1 = (-b + square) / (2*a);
double root2 = (-b - square) / (2*a);
System.out.println("The answer is " + root1 + "and" + root2);
System.out.println("Do you want to continue? y/n");
String user = input.toString();
if(user.equalsIgnoreCase("y"));
}
}
This code:
Math.sqrt(b* b - 4 * a * c );
can result in NaN ("not a number").
If the value of b* b - 4 * a * c is negative, there are solutions only in complex numbers (but not in double data type)
There should be a condition
if (b* b - 4 * a * c<0) {
System.out.println("There is no solution in real numbers");
return;
}
The most likely cause of the problem is Math.sqrt(b*b - 4 * a * c). or one of your input values is NaN (probably not the cause in this situation).
There are two special cases:
b *b < 4 * a * c
and a = 0
if b * b < 4 * a * c your answer is in the complex plane (specifically, not a real number).
if a = 0 then you actually just have a linear equation.
you could try the following code:
package quadratic;
import java.util.Scanner;
public class Formlua {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter value of A ");
double a = input.nextDouble();
System.out.println("enter value of B ");
double b = input.nextDouble();
System.out.println("enter value of C ");
double c = input.nextDouble();
if (a == 0){
// 0 = 0*x*x + b*x + c ==> x = -c/b
System.out.println("X = " + Double.toString(-c/b));
} else {
double inner = b * b - 4 * a * c;
if (inner < 0){
inner = -inner;
inner = Math.sqrt(inner);
System.out.println("X = " + Double.toString(-b) + " + " + Double.toString(inner) + "i")
System.out.println(" = " + Double.toString(-b) + " - " + Double.toString(inner) + "i");
} else {
inner = Math.sqrt(inner);
System.out.println("X = " + Double.toString(-b));
if (inner == 0){
} else {
System.out.println("X = " + Double.toString(-b + inner));
System.out.println("X = " + Double.toString(-b - inner));
}
}
}
}
This lets your user input any double values and recieve an answer.

approximate pi by iteration JAVA

I am trying to approximate pi by iteration. This is only a portion of the code.
I'm trying to put this equation into java: pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 + ... + ((-1)^(i+1)) / (2i - 1) ). The problem I have is the summation of this equation (illustrated in my code). If the user keeps on entering y, the program is supposed to multiply i by 2 and calculate pi until user enters n, then it returns to the main menu.
else if(input == 4)
{
System.out.print("i=1 pi=4.0\tWould you like to continue? (y|n) ");
char y = keyboard.next().charAt(0);
if (y =='y')
{
for (int i=2; i<=1000; i=i*2)
{
int sum = 0;
double pi =4 * (Math.pow(-1, i+1)/(2*i-1));
//Right here, how do I modify it to get a sum across a multitude of i's?
System.out.print("i=" + i + " " + "pi" + "=" + pi + "\tcontinue (y|n)? " );
keyboard.next().charAt(0);
}
}
else
{
}
I think your issue is the difference between the summation equation using i and the programmatic way to loop through a calculation. Something like this will loop through is adding/subtracting the fraction, and then multiply it all by 4 in the end.
boolean plus = true
double sum = 0;
for (double i=1.0; i<=1000; i+=2.0)
{
if (plus) {
sum += 1.0/i;
plus = false;
} else {
sum -= 1.0/i;
plus = true;
}
}
sum *= 4;

Want to loop but variable is not initialized

My problem starts at the first do-while loop. I want it to ask "Please enter an angle between 0 an 90: " and if the user does input a number between 0 and 90, they have to input the amount of gun powder. Their inputs will go through the physics calculations and if their outcome is not "It's a hit!" then I want them to go back and input the angle and gunpowder again. But the thing is at the
while (distance - distance2 != 0 || distance - distance2 != 1 || distance2 - distance != 1); System.out.println("It's a hit!");
The error says: variable distance2 might not have been initialized.
import java.util.*;
import java.text.*;
public class BombsAway {
private static double ZERO_THOUSAND = 1000;
private static double KG_TO_VELOCITY = 50;
private static double GRAVITY = -9.81;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat threeDec = new DecimalFormat("#.##");
Random gen = new Random();
BombsAway distanceAn = new BombsAway();
boolean invalidInput = true;
double distance, distance2;
System.out.println("Please enter a positive integer seed value: ");
while(invalidInput) {
try {
int seedValue = Integer.valueOf(input.nextLine());
if (seedValue <= 0) {
System.out.println("Please enter a positive integer seed value:"
+ " ");
}
else {
distance = gen.nextDouble() * ZERO_THOUSAND;
System.out.println("That target is " + threeDec.format(distance)
+ "m away.");
do {
System.out.println("Please enter an angle between 0 and 90 " +
"degrees: ");
while (invalidInput) {
try {
double angle = Double.valueOf(input.nextLine());
if (angle < 0 || angle > 90) {
System.out.println("Please enter an angle between " +
"0 and 90 degrees: ");
}
else {
System.out.println("Please enter the amount of " +
"gunpowder in kilograms: ");
try {
double gunpowder =
Double.valueOf(input.nextLine());
//physics part
double initialV = gunpowder * KG_TO_VELOCITY;
double vX = initialV * Math.cos(angle);
double vY = initialV * Math.sin(angle);
double airBorn = (-vY - vY) / GRAVITY;
distance2 = (vX * airBorn);
if (distance > distance2) {
double finalDist = distance - distance2;
System.out.println("It's " +
threeDec.format(finalDist) + "m short.");
}
else if (distance < distance2) {
double finalDist = distance2 - distance;
System.out.println("It's " +
threeDec.format(finalDist) + "m long.");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter the amount of " +
"gunpowder in kilograms: ");
}
}
}
catch(NumberFormatException e) {
System.out.println("Please enter an angle between " +
"0 and 90 degrees: ");
}
}
}while (distance - distance2 != 0 || distance - distance2 != 1
|| distance2 - distance != 1);
System.out.println("It's a hit!");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter a positive integer seed value: ");
}
}
}
}
In your code - distance2 is initialized inside one of the conditional blocks (in else block inside while loop) there may be cases when your while or else condition will not be fulfilled and in that case distance2 is left un-initialized and Local variables cannot be used without initialization so simply initialize that distance2 with any meaningful or required default value as:
double distance2 = 0.0; or with some specific value that your code logic works on
The distance2 variable is initialized in a try/catch block. It's possible an exception could be thrown, and land the flow of control in the catch block before distance2 is initialized. After the catch block, distance2 is used in a calculation at the end of the while loop, so yes: it might not be initialized at this line:
while (distance - distance2 == 0 || distance - distance2 == 1
|| distance2 - distance == 1)
if a NumberFormatException was thrown when you are reading the gunpowder or angle values from input. There is also an if condition (bounds check on angle) that could leave distance2 unset.

asks the user for an angle in degrees between 0 and 180

My program accepts any number that I input even 1 million >.<
but I only wanted to ask the user to input an angle in degrees between 0 to 180 and outputs
the sine, cosine and tangent of that angle
here is my program :
import java.util.Scanner;
import java.text.DecimalFormat;
public class Mathematics
{
public static void main(String args[])
{
System.out.println("Enter an Angle ");
Scanner data = new Scanner(System.in);
int x;
x=data.nextInt();
double sinx = Math.sin( Math.toRadians(x) );
double cosx = Math.cos( Math.toRadians(x) );
double tanx = Math.tan( Math.toRadians(x) );
DecimalFormat format = new DecimalFormat("0.##");
System.out.println("Sine of a circle is " + format.format(sinx));
System.out.println("cosine of a circle is " + format.format(cosx));
System.out.println("tangent of a circle is " + format.format(tanx));
}
}
Put this code after x=data.nextInt();
if( x < 0 || x > 180 )
{
throw new Exception("You have entered an invalid value");
}
This will cause your program to crash if the user inputs a number outside the range [0, 180].
If you wish to allow the user to try again, you would need to put the program into a loop, like so:
do
{
System.out.print("Enter a value in [0, 180]: ");
x = data.nextInt();
} while(x < 0 || x > 180);
This loop will continue until the user enters the desired values.
Instead of
x = data.nextInt();
write
do {
x = data.nextInt();
if (x < 0 || x > 180) {
System.out.println("Please enter number between 0-180");
}
} while (x < 0 || x > 180);
Put the question in a loop. When the user enters a value that is outside your range, print an error message and request a different value. When the entered value is OK, then you can exit the loop. It is better to use a function to make things more readable:
public static int askForInt(String question, String error, int min, int max) {
while (true) {
System.out.print(question + " (an integer between " + min + " and " + max + "): ");
int read = new Scanner(System.in).nextInt();
if (read >= min && read <= max) {
return read;
} else {
System.out.println(error + " " + in + " is not a valid input. Try again.");
}
}
}
Call like this: x = askForInt("The angle", "Invalid angle", 0, 180);

Categories