I created a program in Java which makes the user type coordinates of two points, and then the program calculates the slope. Does anyone know how to fix the problem where the program displays the actual slope rather than 0.0?
import java.util.Scanner;
public class Slope
{
public static void main(String[] args)
{
double y1,y2,x2,x1;
float slope = 0;
Scanner SC = new Scanner(System.in);
System.out.println("Enter coordinates for point X1");
x1 = SC.nextDouble();
System.out.println("Enter coordinates for point Y1");
y1 = SC.nextDouble();
System.out.println("Enter coordinates for point X2");
x2 = SC.nextDouble();
System.out.println("Enter coordinates for point Y2");
y2 = SC.nextDouble();
System.out.print("\nThe points are: (" x1 "," y1 ") and (" x2 "," y2 ")");
double Slope = (y2-y1)/(x2-x1);
System.out.println("\nthe slope is:" slope);
}
}
CodePudding user response:
I've recoded it for you, which:
- Solves the problem
- Makes code smaller and non-redundant
- Introduces Modularity
import java.util.Scanner;
public class Slope
{
static Scanner SC = new Scanner(System.in);
public static double double_input(String message)
{
System.out.print(message);
return SC.nextDouble();
}
public static void main(String[] args)
{
double y1, y2, x2, x1, slope = 0;
x1 = double_input("Enter coordinates for point X1 : ");
y1 = double_input("Enter coordinates for point Y1 : ");
x2 = double_input("Enter coordinates for point X2 : ");
y2 = double_input("Enter coordinates for point Y2 : ");
System.out.print("\nThe points are: (" x1 "," y1 ") and (" x2 "," y2 ")");
slope = (y2-y1)/(x2-x1);
System.out.println("\nthe slope is: " slope);
}
}
The problem arose because you've declared and stored the calculated value into another variable 'Slope', but you're printing the other one 'slope'.
CodePudding user response:
You are creating two variables 'slope' and 'Slope'. They are not the same. You are printing the one named 'slope' which is 0 while initializing.
You should print the one called 'Slope' (the later one).