i wrote a bit of java code that calculates distances between 2 points. For some odd reason, it doesn't collect the input nor finds the distance, that is what i am attempting to do. Can someone help me with that, here is my code:

``import java.util.Scanner;public class Distance{static double distance(double x1, double y1, double x2, double y2) {return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));}public static void main(String[] args) {double x2, x1, y2, y1;double distance;Scanner scan = new Scanner (System.in);System.out.println("Enter two points: ");x1 = scan.nextDouble();y1 = scan.nextDouble();x2 = scan.nextDouble();y2 = scan.nextDouble();distance = distance(x1, y1, x2, y2);System.out.println("The distance between the two points is " + distance + " .");}}``

"For some odd reason, it doesn't collect the input nor finds the distance,"

I think the program is waiting for you to enter points still. You're probable currently inputting:

``````5.0 4.5 6.7 4.5
``````

all on the the same line. What happens is that the scanner reads only one double after you hit enter. To fix this, you would have to read the entire line and split it and parse it or just do this

``````                System.out.println("Enter x1: ");
x1 = scan.nextDouble();
System.out.println("Enter x2: ");
y1 = scan.nextDouble();
System.out.println("Enter y1: ");
x2 = scan.nextDouble();
System.out.println("Enter y2: ");
y2 = scan.nextDouble();
``````

Hit enter after every input

If you want to read the entire line. You need to get the input as a String, split it, then parse

``````                String line = scan.nextLine().trim();
String[] tokens = line.split("\\s+");
x1 = Double.parseDouble(tokens);
x2 = Double.parseDouble(tokens);
y1 = Double.parseDouble(tokens);
y2 = Double.parseDouble(tokens);
``````

Top