这是我帮一个同学做的作业,他的作业如下:
作业的主要内容是:
1.读取名为vectors.csv文件。
2.输入一个用户坐标点
3.计算文件中的五个坐标点到原点的距离
4.计算文件中的五个坐标点到输入的用户坐标点的距离
5.输出结果到vectors.csv文件中
实现已经给出了具体的类和方法,主要思路为:
1.读取文件,并使用自定义的ArrayList存储,Point2D为数据结构。
2.Point2D实现具体的计算操作方法,传入x值和y值。
3.将计算结果都存在Point2D数据结构中,并依次写入到文件中。
代码地址:点击打开链接
1.读取文件实现方式:
/**
* @brief Reads from `stream` and adds entries to `list`.
*
* @param stream Scanner providing read access to file.
* @param list ArrayList to store Point2D entries.
*/
public static void readFromFile(Scanner stream, ArrayList<Point2D> list){
try {
stream.useDelimiter("\n");
while (stream.hasNextLine()){
String str = stream.next();
//System.out.println(str);
String [] strings = str.split(";");
Point2D point2D = new Point2D();
point2D.setmName(strings[0]);
point2D.setmX(Double.parseDouble(strings[1]));
point2D.setmY(Double.parseDouble(strings[2]));
list.add(point2D);
}
}catch (Exception e){
e.printStackTrace();
}
}
主方法中关于Stream的调用:
try {
File file = new File("D:vectors.csv");
stream = new Scanner(file);
list = new ArrayList<>();
}catch (Exception e){
e.printStackTrace();
}
2.写文件实现方法:
/**
* @brief Writes entries of `list` to `stream`.
*
* @param list ArrayList of Point2D entries.
*/
public static void writeToFile(ArrayList<Point2D> list){
PrintWriter printWriter = null;
try {
File file = new File("D:testWrite.csv");
if (!file.exists()){
file.createNewFile();
}
printWriter = new PrintWriter(file);
for (int i = 0; i < list.size(); i ++){
String str = list.get(i).getmName() + ";"
+ list.get(i).getmX() + ";"
+ list.get(i).getmY() + ";"
+ list.get(i).getOriginPoint() + ";"
+ list.get(i).getUserPoint() ;
printWriter.println(str);
}
printWriter.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if (printWriter != null){
printWriter.close();
}
}
}
3.Point2D非常强大。
注意点:
1.对计算结果的格式的规范方法:
DecimalFormat df = new DecimalFormat("#.##");
df.format(double)
Double.parseDouble(String)
3.绝对值方法:
Math.abs(类型)
4.命令行输入方法:
Scanner scanner = new Scanner(System.in);
Double.parseDouble(scanner.nextLine());