需要帮助从文件中接受点并将它们添加到数组 Java (Grahams Scan)
Posted
技术标签:
【中文标题】需要帮助从文件中接受点并将它们添加到数组 Java (Grahams Scan)【英文标题】:Need help accepting points from a file and adding them to an array Java (Grahams Scan) 【发布时间】:2016-03-15 03:52:15 【问题描述】:我应该从文件中读取点并将这些点作为数组接受,以便我可以实现 Grahams Scan,但是我的程序似乎只接受第一行点,有人可以帮忙吗?
import java.io.*;
import java.util.*;
public class Graham
private static int[] get_arr(String input) throws Exception
String squirtle;
String[] wartortle;
int[] arr;
//Gets the file
BufferedReader in = new BufferedReader(new FileReader(input));
squirtle = in.readLine();
//delimits numbers with a comma for eventual output
wartortle = squirtle.split(",");
arr = new int[wartortle.length];
//parses values into array
for (int i = 0; i < wartortle.length; i++)
arr[i] = Integer.parseInt(wartortle[i]);
return arr;
public static void main(String[] args) throws Exception
//initializes answer which is used to see if the user wants to repeat the prgm
String answer;
do
String input;
int[] arr;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a source filename such as C:\\Users\\user_\\Documents\\file.txt, or if it's in the same folder as this class just file.txt");
input = scanner.next();
System.out.println("The points");
//Used for outputting file contents
BufferedReader br = new BufferedReader(new FileReader(input));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
//Gather array
arr = get_arr(input);
//Prints array
System.out.println(Arrays.toString(arr));
System.out.println("Thank you for using this program, if you would like to run it again press y if not press anything else");
answer = scanner.next();
//whenever the user inputs y the program runs again
while (answer.equals("y")) ;
my text file called garr.txt looks like
1,2
2,3
3,4
4,5
5,6
但只接受 1,2
【问题讨论】:
【参考方案1】:代码中的问题是您只能从输入文件中读取一行。您应该从文件中读取所有行。您可以按如下方式更改 get_arr 方法:
private static Integer[] get_arr(String input) throws Exception
String squirtle;
List<Integer> intList = new ArrayList<Integer>();
//Gets the file
BufferedReader in = new BufferedReader(new FileReader(input));
while((squirtle = in.readLine()) != null) //Reads all lines
//delimits numbers with a comma for eventual output
String[] wartortle = squirtle.split(",");
for (int i = 0; i < wartortle.length; i++)
intList.add(Integer.parseInt(wartortle[i]));
return intList.toArray(new Integer[0]); //converts Integer list to int[]
【讨论】:
非常感谢,如何更改驱动程序以显示积分? 您的 main 方法将与更新后的 get_arr 方法保持一致。它会起作用的。 别介意固定,你能给我一些关于如何为每两个数字制作一个 x 和 y 点的建议吗? 您可以相应地创建 Point 对象,而不是从 get_arr 返回 Integer[]。检查Point 类。以上是关于需要帮助从文件中接受点并将它们添加到数组 Java (Grahams Scan)的主要内容,如果未能解决你的问题,请参考以下文章