This is my situation:
i need the code to run in a loop, over and over again asking the same question(s) to the user, until the user types a “q” for any point to terminate/exit the loop, thus exiting the program.
The problem is that i tried to used a do-while/while loop, and those loops executes only if the conditions comes out to be true. But i need the condition (“q”) to be false so it can continue the loop. If the condition is true (input.equals(“q”)) , then it just does not nothing because instead of the integer/double, it will use a string (“q”) to calculate the distance.
i have already figured out how to get the distance, the code as is works well, but is there any work-around that i can make the loop continue while the condition is false?
and by the way, i am just barely learning java just in case…
‘.
import java.*;
public class Points {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the first X coordinate: ");
double x1 = input.nextDouble();
System.out.print("Enter the first Y coordinate: ");
double y1 = input.nextDouble();
System.out.print("Enter the second X coordinate: ");
double x2 = input.nextDouble();
System.out.print("Enter the second Y coordinate: ");
double y2 = input.nextDouble();
System.out.println("(" + x1 + ", " + y1 + ")" + " " + "(" + x2 + ", " + y2+ ")");
double getSolution = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
System.out.println(getSolution);
}
}'
The solution to this is to use
String line = input.nextLine()instead ofnextDouble(). Then you can have a method like:This method will need to be called each time the user provides input:
That will exit a loop.
Now, since you have a String representation of the double, you will need to use
Double.parseDouble(line)to turn the String into a number.Then all you have to do is enclose everything in an infinite loop ->
while(true) { }And, the only time it will exit the loop is if the
timeToExitmethod returned true, and you break the loop.This all turns into something like: