package project05demo1; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Test { public static void main(String[] args) throws FileNotFoundException, InvalidTriangleException{ start(); } public static void start() throws FileNotFoundException, InvalidTriangleException { //create an empty list of shapes and save the reference. ArrayList<Shape> ShapeList=new ArrayList<Shape>(); create(ShapeList); //Pass the reference to create method that fills the list. //create(ShapeList); } public static void create(ArrayList<Shape> ShapeList)throws FileNotFoundException,InvalidTriangleException{ //create shape objects using data from an input file. File file=new File("ShapeData.txt"); Scanner InputFile=new Scanner(file); double a,b,c; while(InputFile.hasNext()) { while(InputFile.nextLine()!="Triangle"){ String RectangleName; RectangleName=InputFile.nextLine(); a=InputFile.nextDouble(); b=InputFile.nextDouble(); ShapeList.add(new Rectangle(RectangleName,a,b)); } while(InputFile.nextLine()!="Circle") { String TriangleName; TriangleName=InputFile.nextLine(); a=InputFile.nextDouble(); b=InputFile.nextDouble(); c=InputFile.nextDouble(); ShapeList.add(new Triangle(TriangleName,a,b,c)); } while(InputFile.hasNextLine()) { String CircleName; CircleName=InputFile.nextLine(); a=InputFile.nextDouble(); ShapeList.add(new Circle(CircleName,a)); } } InputFile.close(); } public static void display(ArrayList<Shape> ShapeList) { for(int i=0;i<ShapeList.size();i++) { System.out.println(ShapeList.get(i)); } } }
时间: 2024-01-08 22:02:00 浏览: 126
java代码-import java.util.Scanner;
5星 · 资源好评率100%
这是一个Java程序,用于读取一个包含不同形状数据的文件,并创建相应的形状对象。程序包含三个类:Shape、Rectangle、Triangle和Circle。其中Shape是所有形状的基类,而Rectangle、Triangle和Circle是Shape的子类。程序使用ArrayList来存储所有创建的形状对象,并提供了一个display方法,用于打印所有形状对象的信息。
该程序还涉及到一个InvalidTriangleException异常类,用于在创建Triangle对象时检查是否为有效的三角形。程序的主方法是start方法,它调用create方法来读取文件并创建形状对象,然后调用display方法来打印形状对象的信息。
阅读全文