0

我应该从文件中读取点并将这些点作为数组接受,以便我可以实现 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

4

1 回答 1

0

代码中的问题是您只从输入文件中读取单行。您应该从文件中读取所有行。您可以按如下方式更改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[]
}
于 2016-03-15T04:34:43.983 回答