首页 > 解决方案 > 从每两个整数创建一个点

问题描述

我必须使用 Scanner 读取整数文件并创建“n”个点。下面是一个文件示例:

4 110 115 112 112 140 145 130 190
3 125 125 130 150 110 110

开头的数字 5 和 4 代表我需要创建的 Point 对象的数量,之后,每两个整数必须从一个 Point 中创建。以下是输出示例:

OUTPUT:
[(110, 115), (112, 112), (140, 145), (130, 190)]
[(125, 125), (130, 150), (110, 110)]

我怎么可能在每一行中循环,并选择将每两个整数分开以形成一个 Point 对象?

标签: javaoop

解决方案


使用此代码:

    String text = "3 125 125 130 150 110 110";
    //First of all you have to split your text to get array of numbers
    String[] splitted_text = text.split(" ");
    //the first number of array represents the point count
    //so declare an array of points by this count
    Point[] points = new Point[Integer.parseInt(splitted_text[0])];

    //numbers in odd positions starting from 1 represent x
    //numbers in even positions starting from 2 represent x
    //so you can form points using numbers in even and odd positions
    for (int i = 0; i < points.length; i++) {
        points[i].x=Integer.parseInt(splitted_text[2*i + 1]);
        points[i].y=Integer.parseInt(splitted_text[2*i + 2]);            
    }

推荐阅读