Java 从每两个整数创建一个点
我必须使用扫描仪读取一个整数文件,并创建“n”个点数。以下是一个文件示例:Java 从每两个整数创建一个点,java,oop,Java,Oop,我必须使用扫描仪读取一个整数文件,并创建“n”个点数。以下是一个文件示例: 4 110 115 112 112 140 145 130 190 3 125 125 130 150 110 110 开头的数字5和4表示我需要创建的点对象的数量,之后,每两个整数必须创建一个点。以下是一个输出示例: OUTPUT: [(110, 115), (112, 112), (140, 145), (130, 190)] [(125, 125), (130, 150), (110, 110)] 我如何可能在
4 110 115 112 112 140 145 130 190
3 125 125 130 150 110 110
开头的数字5和4表示我需要创建的点对象的数量,之后,每两个整数必须创建一个点。以下是一个输出示例:
OUTPUT:
[(110, 115), (112, 112), (140, 145), (130, 190)]
[(125, 125), (130, 150), (110, 110)]
我如何可能在每一行中循环,并选择将每两个整数分开以形成一个点对象?使用以下代码:
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]);
}
String text=“3 125 130 150 110”;
//首先,您必须拆分文本以获得数字数组
String[]splitted_text=text.split(“”);
//数组的第一个数字表示点计数
//因此,根据此计数声明一个点数组
点[]点=新点[Integer.parseInt(拆分的_文本[0]);
//从1开始的奇数位置的数字表示x
//从2开始的偶数位置的数字表示x
//所以你可以用偶数和奇数的数字来形成点
对于(int i=0;i
主要类别:
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));
}
}
}
谷歌搜索“如何用Java阅读行”。然后谷歌搜索“如何在Java中拆分字符串”。然后,希望您了解循环,否则请通过谷歌搜索“如何在Java中使用循环”。简而言之:把问题分成简单的任务,做一些研究,然后做一些尝试。文档、教程等都是免费提供的。到目前为止,您尝试了什么?我的意思是我可以阅读文件并循环每一行,但是我找不到一种方法来分别拆分每两个整数。您可以添加更多信息吗?(到目前为止,你得到了什么,你想在哪里输出到[file/console/create object])所以,谷歌搜索“如何在Java中拆分字符串”。然后使用循环将结果中的数字2乘以2进行组合。您可以解释代码,以便人们可以从中学习,而不仅仅是复制和粘贴代码。
public class Point{
int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public String toString(){
return "(" + x + ", " + y + ")";
}
}