java - 从每两个整数创建一个点
问题描述
我必须使用 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 对象?
解决方案
使用此代码:
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]);
}
推荐阅读
- excel - EXCEL 获取重复数组中的前 3 个最大数
- r - 使用 ggplot 在分组条形图中获取计数而不是百分比
- excel - Excel 中是否有类似 Application.Intersect(Target, Range) 的谷歌脚本方法?
- java - 多部分文件到 .zip
- css - bootstrap 4 中心标题和右对齐按钮都在一行中
- google-chrome-extension - 使用 Chrome 扩展获取 DOM 内容
- r - 通过在 R 中随时间增加计数来子集
- sql-server - 我们可以用相同的主键制作不同表链接的多个外键吗?
- c++ - 模板上的运算符重载
- ios - 无法使用 Codable 和 Alamofire 3.0 解析数据