I’m working on a homework problem for class. Where you have to calculate the distance between two points. The code is basically done, but I have one question. When I enter q to end the loop. I get a message back.
Exception in thread “main” java.lang.NumberFormatException: For input string: “q”
at.sun.misc.FloatingDecimal.readJavaFormatString(Unkown Source)
at java.lang.Double.parseDouble(Unkown Source)
atDistance.main(Distance.java:11)
import java.util.Scanner;
public class Distance {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter coordinate for x1: ");
String x1String = input.next();
if (x1String == "q")
break;
double x1 = Double.parseDouble(x1String);
System.out.print("Enter coordinate for y1: ");
String y1String = input.next();
if (y1String == "q")
break;
double y1 = Double.parseDouble(y1String);
System.out.print("Enter coordinate for x2: ");
String x2String = input.next();
if (x2String == "q")
break;
double x2 = Double.parseDouble(x2String);
System.out.print("Enter coordinate for y2: ");
String y2String = input.next();
if (y2String == "q")
break;
double y2 = Double.parseDouble(y2String);
double distance = (Math.pow(x2 - x1,2)) + (Math.pow(y2 - y1,2));
distance = Math.sqrt(distance);
System.out.printf("The distance is %5.2f",distance);
System.out.println("");
}
}//main
}//Distance
That is the code I have written. Any help is appreciated.
You don’t do a string compare with ==. The “==” comparison checks to see if they are the exact same objects, not if the strings contain the same characters. Try
x1String.equals("q")instead.What’s happening now is that the “==” will say “these aren’t the same object” and then it will attempt to parse the “q” as a double in the next line, which is throwing the exception.