问题
GeometricObjectsData.txt
“CIRCLE”, 1, “blue”, true
“RECTANGLE”, 1, 2, “blue”, true
“RECTANGLE”, 10, 2, “red”, true
“CIRCLE”, 2, “green”
“RECTANGLE”
“CIRCLE”
Driver: I'm a bit confused on how to transfer the above information into an object and then assign it to an array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("C:/Users/Charles/Desktop/GeometricObjectsData.txt"));
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
}
}
}
I also have created 3 other classes called GeometricObject, Circle, and Recetangle if you want to see the code for them. The information above indicates the type of figure and the given parameters of radius, length, width, color, and filled.
回答1:
As microsby0 said, you could probably split the raw words into arrays. I don't believe there is an easy way to directly convert a raw word into a class name ((Circle)"Circle" doesn't work and is what I believe is confusing you). You should read each array into certain parameters and process them:
/*somewhere else in code:*/ shapeArray[i] = convert(array[0],array[1],...)//where i is some incremental value in a loop
Shape convert(String s, int someNumber,...) {
Shape c;
switch(s) {
case "Circle":
c = new Circle(...);
break;
case "Square"
...
break;
//and so on
}
//more application logic
return c;
}
Convert can return a shape which you can assign to an array of shapes. You can always use function(method) 'overloading' to handle different inputs.
回答2:
PSUEDOCODE is used:
I probably wouldn't use a Scanner but
BufferedReader buffer = new BufferedReader(new FileReader(file));
then you would
//this should split the text of each line into an array
String buf[]= null;
while ((line = buffer.readLine()) != null) {
resultLine += line + ";";
buf = resultLine.split(";");
}
buffer.close();
then looped through the array buf and do
if(buf[i].startsWith("C"))
then do another split on buf[i] using "," into another array like String arr[]
arr = buf[i].split(",");
then but the elements of the second array in the Circle Class like
Circle circle = new Circle(arr[0],arr[1],etc
then add to an array
Object result[] = new Object[100];
result[0] = circle;
来源:https://stackoverflow.com/questions/26241322/how-to-read-data-from-a-file-and-create-an-object-and-assign-it-to-an-array