Hello,
I am a new programmer and am having trouble with some instructions i have to create a program. I am suppose to make a service class called CreateVehicles. In this class I am supposed to declare some instance variables, then create constructors, mutators, accessors, and a helper method. I think my code is fine for the first three, but the compiler complains about the way I try to enter the data from the file into an array using a while loop. These are the instructions I was given.
Create a class called CreateVehicles. This class acts as a second service class. The task of this class is to provide instance variables , constructors, accessor/mutator methods and a helper method that allow the following tasks to be performed:
• The helper method has the task of reading the text file (Vehicle.txt) that contains information about different vehicles (one line per Vehicle). You need to tokenize each line read by the scanner in order to get the individual pieces of data that the constructor of the Vehicle class needs. Therefore, for each line of data read you create a Vehicle object and then you enter that object into an array of Vehicle type. The method returns the array with the vehicle objects.
• Decide which instance variables you need to declare for this class based on the description of its task.
• Create the text file Vehcicles.txt using Notepad with the following data (similar to the project data):
An this is what I have for the class.
import java.io.File; import java.io.IOException; import java.util.Scanner; public class CreateVehicles { String cartype = " "; String cardrive = " "; int carprice = 0; public CreateVehicles() { cartype = "anytype"; cardrive = "anydrive"; carprice = 0; } public CreateVehicles(String ct, String cd, int cp) { cartype = ct; cardrive = cd; carprice = cp; } public String getcartype() { return cartype; } public String getcardrive() { return cardrive; } public int getcarprice() { return carprice; } public void setcartype(int cat) { cartype = cat; } public void setcardrive(int cad) { cardrive = cad; } public void setcarprice(int cap) { carprice = cap; } public CreateVehicles [] createArray() { CreateVehicles [] myvehicles = new CreateVehicles[8]; try { File myfile = new File("Vehicle.txt"); Scanner scan = new Scanner(myfile); while(scan.hasNext()) { str=scan.next(); str.myvehicles[]; } } catch(IOException ion) { System.out.println("The file cannot be read"); } } }
I am certain I messed something up in the while loop. Any input or hints would be greatly appreciated.
Thanks.