Question: I am trying to generate the distance formula based on user input, however, I keep getting a error when the program is run. Please explain

I am trying to generate the distance formula based on user input, however, I keep getting a error when the program is run. Please explain what is the issue with my code(I've also included the error below the code):

package labchapt3;

import java.text.DecimalFormat; import java.util.Scanner; import java.text.NumberFormat;

public class LabChapt3 {

public static void main(String[] args) { Scanner scan = new Scanner(System.in);

System.out.println("***********Calculate Distance Between Two Points*********** " + "Enter coorinates of two points in the following format: " + "\t(x1,y1);(x2,y2)");

String sInput = scan.nextLine();

sInput = sInput.replace(" ", ""); sInput = sInput.replace(")", ""); sInput = sInput.replace("(", ""); sInput = sInput.replace(",", "");

int index = sInput.indexOf(";");

String sCoor1 = sInput.substring(0, index);

String sCoor2 = sInput.substring(0, index);

index = sCoor1.indexOf(","); String sX = sCoor1.substring(0, index); String sY = sCoor1.substring(index +1);

index = sCoor2.indexOf(","); String sX2 = sCoor2.substring (0, index); String sY2 = sCoor2.substring(index +1);

double x1 = Double.parseDouble(sX); double y1 = Double.parseDouble(sY); double x2 = Double.parseDouble(sX2); double y2 = Double.parseDouble(sY2);

double dSub1 = Math.pow(x2-x1,2); double dSub2 = Math.pow(y2-y1,2);

double result = Math.sqrt(dSub1 + dSub2); NumberFormat format = new DecimalFormat("#0.0000"); System.out.println("The distance is: " + format.format(result) + "units");

} }

Error:

run:

***********Calculate Distance Between Two Points***********

Enter coorinates of two points in the following format:

(x1,y1);(x2,y2)

(545334,23323);(5522,-544)

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

at java.lang.String.substring(String.java:1967)

at ch03_lab2_melissaforsee.Ch03_Lab2_MelissaForsee.main(Ch03_Lab2_MelissaForsee.java:36)

C:\Users\Melissa\AppData\Local\NetBeans\Cache\8.2\executor-snippets un.xml:53: Java returned: 1

BUILD FAILED (total time: 23 seconds)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!