So I have looked at a couple of related questions, but still can't seem to find my answer (I guess because it's specific). I'm trying to use the Scanner.useDelimiter method in Java and I can't get it to work properly... here is my dilemma...
We are supposed to write a program that takes a X, Y coordinate and calculates the distance between the two points. Obviously, one solution is to scan for each x and y coordinate separately, but this is sloppy to me. My plan is to ask the user to input the coordinate as "x, y" and then grab the integers using the Scanner.nextInt() method. However, I have to find a way to ignore the "," and of course, I can do that with the useDelimiter method.
According to other threads, I have to understand regex (not there yet) to put in the useDelimiter method and I've got it to ignore the commas, HOWEVER, there is a possibility that a user inputs a negative number as a coordinate (which is technically correct). How do I get useDelimiter to ignore the comma, but still recognize the negative sign?
This is my first time on here, here is my code:
import java.util.Scanner;
import java.text.DecimalFormat;
public class PointDistanceXY
{
public static void main(String[] args)
{
int xCoordinate1, yCoordinate1, xCoordinate2, yCoordinate2;
double distance;
// Creation of the scanner and decimal format objects
Scanner myScan = new Scanner(System.in);
DecimalFormat decimal = new DecimalFormat ("0.##");
myScan.useDelimiter("\\s*,?\\s*");
System.out.println("This application will find the distance between two points you specify.");
System.out.println();
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
xCoordinate1 = myScan.nextInt();
yCoordinate1 = myScan.nextInt();
System.out.print("Enter your second coordinate (format is \"x, y\"): ");
xCoordinate2 = myScan.nextInt();
yCoordinate2 = myScan.nextInt();
System.out.println();
// Formula to calculate the distance between two points
distance = Math.sqrt(Math.pow((xCoordinate2 - xCoordinate1), 2) + Math.pow((yCoordinate2 - yCoordinate1), 2));
// Output of data
System.out.println("The distance between the two points specified is: " + decimal.format(distance));
System.out.println();
}
}
Thanks for your help and I look forward to helping other people down the line!