Distance between two points, and q to exit

This is my situation:

I need code to start the cycle over and over, asking the same question to the user until the user types “q” for any point to end / exit the cycle, thereby exiting the program.

The problem is that I tried to use the do-while / while loop, and these loops execute only if the conditions are true. But I need the condition ("q") to be false in order to continue the loop. If the condition is true (input.equals ("q")), then it just has nothing, because instead of the integer / double, it will use the string ("q") to calculate the distance.

I already figured out how to get the distance, the code works fine, but is there any work so that I can make the loop last while the condition is false?

and by the way, I just don't learn much 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);
    }
}'
+3
source share
3 answers

The solution to this is to use String line = input.nextLine()instead nextDouble(). Then you can have a method like:

public static boolean timeToExit(String input) {
    return input.equalsIgnoreCase("q");
}

This method will need to be called every time the user provides input:

if (timeToExit(line)) break;

This will exit the loop.

Now, since you have a string representation of the double, you will need to use Double.parseDouble(line)to turn String into a number.

Then all you have to do is enclose everything in an infinite loop → while(true) { }

, , , timeToExit true, .

- :

while (true) {
    ...
    System.out.print("Enter the first X coordinate: ");
    String x1 = input.nextLine();
    if (timeToExit(x1)) break;
    double x1_d = Double.parseDouble(x1);
    ...
}
+1

:

while (! input.equals("q") )
// do something

q, input.equals( "q" ) true, .

, 44, input.equals( "q" ) false, .

+1

I do not see the loop in your code ...: s

But why don't you try:

while(true)
{
  string input = // I don't remember the code to create a stream for standard input
  if(input == "q"){
    break;
  }
  else{
    java.util.Scanner inputWithNumbers = new java.util.Scanner(input);
    //---! All math operations here
  }
}
0
source

Source: https://habr.com/ru/post/1770188/


All Articles