2014-01-15 1 views
0

Мне нужна помощь в назначении моей Java-программы. Назначение - вычисление расстояния между двумя точками с помощью java. Я закончил первую часть, как следует:Несколько входов с той же строки в java

import java.util.Scanner; 

public class DistanceCalcEasy 
{ 
    public static void main(String[] args) 
    { 
    // Creating a new scanner object 
    System.out.println("Distance Calculator"); 
    Scanner input = new Scanner(System.in); 

    // Getting all of the coordinates 
    System.out.print("Enter the X coordinate of the first point: "); 
    double x1 = input.nextDouble(); 
    System.out.print("Enter the Y coordinate of the first point: "); 
    double y1 = input.nextDouble(); 

    System.out.print("Enter the X coordinate of the second point: "); 
    double x2 = input.nextDouble(); 
    System.out.print("Enter the Y coordinate of the second point: "); 
    double y2 = input.nextDouble(); 

    // Calculating the distance between the points 
    double distance = Math.sqrt(Math.pow((x2-x1),2) + Math.pow((y2-y1),2)); 

    // Printing the distance to the User 
    System.out.println("The distance between the points is " + distance); 
    } 
} 

Теперь проблема мне нужно сделать эту же программу еще раз, но «трудный путь», позволяя пользователю ввести координату как 1,2 вместо каждого х и у на их собственной линии. Это то, что я начал придумывать после небольшого исследования:

import java.util.Scanner; 

public class DistanceCalcHard 
{ 
    public static void main(String[] args) 
    { 
     // Creating a new Scanner Object 
     System.out.println("Distance Calculator"); 
     Scanner input = new Scanner(System.in); 

     // Getting the data points 
     System.out.print("Enter the first point x,y: "); 
     String firstPoint = input.nextLine(); 

     System.out.print("Enter the second point x,y: "); 
     String secondPoint = input.nextLine(); 

     Scanner scan = new Scanner(firstPoint).useDelimiter("\\s*,\\s*"); 
     while (scan.hasNextDouble()) 
     { 

     } 
     // Calculating the distance 

     // Displaying the distance to the user 
    } 
} 

Это похоже на хорошее начало? Я думал, что могу сделать два массива, по одному для каждой точки, а затем сделать расчет расстояния таким образом. Есть ли более простой способ сделать это, или кто-то может указать мне в лучшем направлении? Спасибо

+0

'ИНТ [] point1 = firstPoint.split ("")' дать вам точку в массиве '[1, 2]', например, – Baby

ответ

0

Как о чем-то вроде этого: (т. Е х, у -> х и у)

import java.util.Scanner; 

public class DistanceCalcEasy 
{ 
    public static void main(String[] args) 
    { 
    // Creating a new scanner object 
    System.out.println("Distance Calculator"); 
    Scanner input = new Scanner(System.in); 

    // Getting all of the coordinates 
    System.out.print("Enter the X,Y coordinate of the first point: "); 
    String xy1in = input.nextLine(); 

    System.out.print("Enter the X,Y coordinate of the second point: "); 
    String xy2in = input.nextLine(); 

    String[] xy1 = xy1in.split(","); 
    String[] xy2 = xy2in.split(","); 

    double x1 = Double.parseDouble(xy1[0]); 
    double y1 = Double.parseDouble(xy1[1]); 
    double x2 = Double.parseDouble(xy2[0]); 
    double y2 = Double.parseDouble(xy2[1]); 

    // Calculating the distance between the points 
    double distance = Math.sqrt(Math.pow((x2-x1),2) + Math.pow((y2-y1),2)); 

    // Printing the distance to the User 
    System.out.println("The distance between the points is " + distance); 
    } 
} 
1

простой способ идти о расщеплении строку в двух значений будет с помощью оператора split() для объекта String.

String[] pointA = firstPoint.split(","); 

И то же самое можно сделать для второго пункта. Теперь у вас есть две точки в массивах, где pointA[0] - это значение x, а pointA[1] - значение y.

Дополнительную документацию о методе можно найти here

Смежные вопросы