每两个整数创建一个点

时间:2018-07-07 10:20:37

标签: java oop

我必须使用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对象?

2 个答案:

答案 0 :(得分:2)

使用此代码:

    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]);            
    }

答案 1 :(得分:0)

主类:

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line;

        //read line untill it's not null or empty
        while ((line = in.nextLine()) != null && !line.isEmpty()) {
            //split line by regex \s (whiteSpace chars)
            String[] ints = line.split("\\s");
            //our array could be empty if there was just spaces in line
            if (ints.length == 0)
                return;

            //Think it's understandable
            int count = Integer.parseInt(ints[0]);
            Point[] points = new Point[count];

            //according to line structure, x and y of point number i would be
            // i * 2 + 1 and i * 2 + 2
            for (int i = 0; i < count; ++i) {
                int x = Integer.parseInt(ints[i * 2 + 1]);
                int y = Integer.parseInt(ints[i * 2 + 2]);
                points[i] = new Point(x, y);
            }

            //To achieve output like yours, use Arrays.toString()
            System.out.println(Arrays.toString(points));
        }
    }
}

积分班:

public class Point{
int x, y;

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

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