计算点之间的距离 Java

huangapple go评论61阅读模式
英文:

Calculating distance between dots java

问题

我的任务是从文件中加载坐标,并计算形状的周长。
dots.txt 的示例:

-3, 9
-8, 7
-12, 4
-6, -2
-4, -6
2, -8
6, -5
10, -3
8, 5
4, 8

我创建了一个非常简单的 Dot.class,其中包含一个计算两个点之间距离的方法。

public class Dot {
    int x;
    int y;

    public Dot(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public double calcDistance(Dot anotherDot) {
        int dx = x - anotherDot.x;
        int dy = y - anotherDot.y;
        return Math.sqrt((dx*dx) + (dy*dy));
        //编辑:与下面的代码效果相同
        //return Math.hypot(x - anotherDot.x, y - anotherDot.y);
    }

    public String toString() {
        return "" + x + y;
    }
}

以下是我的主要方法:

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        //读取文件
        FileReader fr = new FileReader("src/com/company/dots.txt");
        Scanner inFile = new Scanner(fr);
        ArrayList<Dot> dots = new ArrayList<>();

        while (inFile.hasNext()) {
            // 读取下一行。
            String[] line = inFile.nextLine().split(",");
            // 显示该行。
            int x = Integer.parseInt(line[0]);
            int y = Integer.parseInt(line[1].replace(" ", ""));
            System.out.println(x + " " + y);
            dots.add(new Dot(x, y));
        }

        System.out.println("ArrayList 的大小:" + dots.size());

        // 关闭文件。
        inFile.close();
    }
}

请帮我计算周长,因为我在这方面遇到了困难...
提前感谢!

编辑:
我设法编写了一个简单的 for 循环,计算点之间的距离,然后将其相加。

int lastDot = dots.size() - 1;
double perimeter = 0;
for (int i = 0; i < dots.size(); i++) {
    // 检查是否为最后一个点,然后计算最后一个点与第一个点之间的距离。
    if (i == lastDot) {
        perimeter += dots.get(lastDot).calcDistance(dots.get(0));
    } else {
        perimeter += dots.get(i).calcDistance(dots.get(i + 1));
    }
}
英文:

My task is to load coordinates from a file, and calculate perimeter of the shape.
example of dots.txt

-3, 9
-8, 7
-12, 4
-6, -2
-4, -6
2, -8
6, -5
10, -3
8, 5
4, 8

I have created a Dot.class which is quite simple, with an method to calculate distance between 2 dots.

public class Dot {
    int x;
    int y;

    public Dot(int x, int y)
    {
        this.x = x;
        this.y = y;
    }


    public double calcDistance(Dot anotherDot)
    {
        int dx = x - anotherDot.x;
        int dy = y - anotherDot.y;
        return Math.sqrt((dx*dx) + (dy*dy));
//EDIT: WORKS SAME AS
//return Math.hypot(x - anotherDot.x, y - anotherDot.y);
    }

    public String toString(){
        return &quot;&quot; + x + y;
    }
}

Here is my Main method:

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        //read file
        FileReader fr = new FileReader(&quot;src/com/company/dots.txt&quot;);
        Scanner inFile = new Scanner(fr);
        ArrayList&lt;Dot&gt; dots = new ArrayList&lt;&gt;();

        while (inFile.hasNext())
        {
            // Read the next line.
            String [] line = inFile.nextLine().split(&quot;,&quot;);
            // Display the line.
            int x = Integer.parseInt(line[0]);
            int y = Integer.parseInt(line[1].replace(&quot; &quot;, &quot;&quot;));
            System.out.println(x + &quot; &quot; + y);
            dots.add(new Dot(x, y));
        }

        System.out.println(&quot;size of the ArrayList: &quot; + dots.size());


        // Close the file.
        inFile.close();

    }
}

Please help me with calculating perimeter because I am pretty stuck with this one..
Thanks in advance

EDIT:
Managed to write a simple for-loop to calculate distance between dots and then sum it up.

int lastDot = dots.size() - 1;
double perimeter = 0;
    for(int i = 0; i&lt; dots.size(); i++)
    {
//check if its the last dot, then calculate distance between the last dot and the first one.
        if(i==lastDot){ 
            perimeter += dots.get(lastDot).calcDistance(dots.get(0));
        } else
        perimeter += dots.get(i).calcDistance(dots.get(i+1));
    }

答案1

得分: 2

你是否尝试过类似这样的方式:

double dist=0;
for(int i=0;i<dots.size();i++){
   dist+= dots.get(i%dots.size()).calcDistance((i+1)%dots.size());
}

或者你是指像更复杂的情况,比如避免线段交叉?

英文:

Have you tried something like:

double dist=0;
for(int i=0;i&lt;dots.size();i++){
   dist+= dots.get(i%dots.size()).calcDistance((i+1)%dots.size());
}

or you mean something more complex like not having crossing of lines?

答案2

得分: 0

public static void main(String... args) throws FileNotFoundException {
    List<Dot> dots = readData(new FileReader("src/com/company/dots.txt"));
    System.out.println("List 的大小:" + dots.size());
    double perimeter = getShapePerimeter(dots);
    System.out.format(Locale.ENGLISH, "形状周长:%.2f\n", perimeter);
}

private static List<Dot> readData(Reader reader) throws FileNotFoundException {
    try (Scanner scan = new Scanner(reader)) {
        scan.useDelimiter(",\\s*|\\n");

        List<Dot> dots = new ArrayList<>();

        while (scan.hasNext()) {
            int x = scan.nextInt();
            int y = scan.nextInt();
            dots.add(new Dot(x, y));
        }

        return dots;
    }
}

private static double getShapePerimeter(List<Dot> dots) {
    double res = 0;
    Dot prv = dots.get(dots.size() - 1);

    for (Dot dot : dots) {
        res += Math.hypot(dot.x - prv.x, dot.y - prv.y);
        prv = dot;
    }

    return res;
}

public static final class Dot {

    private final int x;
    private final int y;

    public Dot(int x, int y) {
        this.x = x;
        this.y = y;
    }

}
英文:
public static void main(String... args) throws FileNotFoundException {
List&lt;Dot&gt; dots = readData(new FileReader(&quot;src/com/company/dots.txt&quot;));
System.out.println(&quot;size of the List: &quot; + dots.size());
double perimeter = getShapePerimeter(dots);
System.out.format(Locale.ENGLISH, &quot;shape perimeter: %.2f\n&quot;, perimeter);
}
private static List&lt;Dot&gt; readData(Reader reader) throws FileNotFoundException {
try (Scanner scan = new Scanner(reader)) {
scan.useDelimiter(&quot;,\\s*|\\n&quot;);
List&lt;Dot&gt; dots = new ArrayList&lt;&gt;();
while (scan.hasNext()) {
int x = scan.nextInt();
int y = scan.nextInt();
dots.add(new Dot(x, y));
}
return dots;
}
}
private static double getShapePerimeter(List&lt;Dot&gt; dots) {
double res = 0;
Dot prv = dots.get(dots.size() - 1);
for (Dot dot : dots) {
res += Math.hypot(dot.x - prv.x, dot.y - prv.y);
prv = dot;
}
return res;
}
public static final class Dot {
private final int x;
private final int y;
public Dot(int x, int y) {
this.x = x;
this.y = y;
}
}

Output:

size of the List: 10
shape perimeter: 59.46

huangapple
  • 本文由 发表于 2020年9月21日 00:57:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63981502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定