2015-12-07 3 views
-4
import java.io.*; 
public class Point { 
    private double x; 
    private double y; 
    public Point(double x_coord, double y_coord) { 
     x = x_coord; 
     y = y_coord; 
    } 
} 
public class PointArray { 
    private Point points[]; 
    public PointArray(FileInputStream fileIn) throws IOException { 
     try { 
      BufferedReader inputStream = new BufferedReader(new InputStreamReader(fileIn)); 
      int numberOfPoints = Integer.parseInt(inputStream.readLine())...points = new Point[numberOfPoints]; 
      int i = 0; 
      String line; 
      while ((line = inputStream.readLine()) != null) { 
       System.out.print(line); 
       double x = Double.parseDouble(line.split(" ")[0]); 
       double y = Double.parseDouble(line.split(" ")[1]); 
       points[i] = new Point(x, y); 
       i++; 
      } 
      inputStream.close(); 
     } catch (IOException e) { 
      System.out.println("Error"); 
      System.exit(0); 
     } 
    } 
} 
public String toString() { 
    String format = "{"; 
    for (int i = 0; i < points.length; i++) { 
     if (i < points.length - 1) format = format + points[i] + ", "; 
     else format = format + points[i]; 
    } 
    format = format + "}"; 
    return format; 
} 
public static void main(String[] args) { 
    FileInputStream five = new FileInputStream(new File("fivePoints.txt")); 
    PointArray fivePoints = new PointArray(five); 
    System.out.println(fivePoints.toString()); 
} 

Файл текстовый fivePoints будет, как показано ниже:не можете прочитать текстовый файл

5 
2 7 
3 5 
11 17 
23 19 
150 1 

Первое число в первой строке означает количество точек в текстовом файле. При чтении файла произошла ошибка. Выход, который я хочу получить, это {(2.0, 7.0), (3.0, 5.0), (11.0,17.0), (23.0, 19.0), (150.0, 1.0)}. Как я могу это исправить?

+0

Ну, метод toString должен быть объявлен в методе 'PointArray' – MadProgrammer

+0

Я делаю, но он не работает. – Chriseagles

+0

Нет, в вашем примере кода 'toString' объявляется стороной метода' PointArray', поэтому он не будет – MadProgrammer

ответ

2

Добавьте метод toString к вашему Point который форматирует Point в x, y

public class Point { 
    //...   
    @Override 
    public String toString() { 
     return x + ", " + y; 
    } 
} 

Переместить ваш метод toString так это определено в PointArray, вы могли бы также рассмотреть возможность использования StringJoiner, чтобы сделать вашу жизнь проще

public class PointArray { 
    //... 
    @Override 
    public String toString() { 
     StringJoiner sj = new StringJoiner(", ", "{", "}"); 
     for (int i = 0; i < points.length; i++) { 
      sj.add("(" + points[i].toString() + ")"); 
     } 
     return sj.toString(); 
    } 
} 
Смежные вопросы