I'm making a program that writes the equation of a line for the user, given 2 x and y-intercepts. The "else" without "if" error is happening on line 46 when I try to calculate the y-intercept for a negative number. I'm pretty new to coding, so any help or suggestions would be greatly appreciated.
I tried to use just if statements, but then the issue is that the variable b is already declared, and I've also fiddled with squiggly brackets but those haven't worked for me too.
import java.io.*;
//Calculates the y=mx+b for user.
class YMXB
{
public static void main(String args[]) throws Exception
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("This program calculates the equation of a line (y=mx+b) for you.");
//Input for coordinates
double x1;
System.out.print("Please enter x coordinate #1: ");
x1=Double.parseDouble(br.readLine());
double y1;
System.out.print("Please enter y coordinate #1: ");
y1=Double.parseDouble(br.readLine());
double x2;
System.out.print("Please enter x coordinate #2: ");
x2=Double.parseDouble(br.readLine());
double y2;
System.out.print("Please enter y coordinate #2: ");
y2=Double.parseDouble(br.readLine());
//calculating slope
double m=(y2)-(y1)/(x2)-(x1);
//calculating y-intercept
double x3=(m)*(x1);
//if statements for +x3
if (x3<0)
x3=Math.abs(x3);
double b=(y1)+(x3);
//if statements for -x3
else if(x3>0)
x3*=(-1);
double b=(y1)-(x3);
//calculating x and y
double y= (y2)-(y1);
double x= (x2)-(x1);
//if statements for horizontal lines
if (y==0) {
System.out.print("This is a horizontal line.");
System.out.print("y= "+x);
}
//if statements for horizontal lines
if (x==0) {
System.out.print("This is a vertical line.");
System.out.print("y= "+y);
}
//y-intercept greater than 0
if (b>0){
System.out.println("The equation of your line is y= "+m+"x+"+b);
}
//y-intercept less than 0
if (b<0){
System.out.println("The equation of your line is y= "+m+"x"+b);
}
}
}
When the user inputs the numbers the program should give the statement y=mx+b or y=mx-b, depending on if the y-intercept is positive or negative.
Aucun commentaire:
Enregistrer un commentaire