I'm working on a project which reads from csv file, then uses StringTokenizer to chop up the elements and place them into JLabels. So far I have that part down. I have buttons to scroll through each position, but I'm not sure about how I can type in the fields and add on to the array ?
This is the main part of my program so far
// program reads in csvfile.
private void loadCarList() {
try{
BufferedReader CSVFile = new BufferedReader(new FileReader("car.txt"));
String dataRow = CSVFile.readLine();
while(dataRow != null){
carList.add(dataRow);
dataRow = CSVFile.readLine();
}
}catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}
//this will click cycle through the elements in the Jlabels.
private void loadNextElement(){
try {
StringTokenizer st = new StringTokenizer((String)carList.get(position), ",");
while(st.hasMoreTokens() && position <= carList.size() -1) {
position ++;
String CarID = st.nextToken();
String DealerShipID = st.nextToken();
String ColorID = st.nextToken();
String Year = st.nextToken();
String Price = st.nextToken();
String Quantity = st.nextToken();
tCarID.setText(CarID);
tDealerShip.setText(DealerShipID);
tColor.setText(ColorID);
tYear.setText(Year);
tPrice.setText(Price);
tQuantity.setText(Quantity);
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, "youve reached the end of the list");
}
}
Is there a simpler way where I can just type in the jlabels I have laid out and add onto the array?
I'm kind of lost at this point, and am unsure how to go further with this.
Your problem appears to be that you're trying to do too much inside one class. It's possible to do, but not very well organized.
Create a separate class for holding a single Car record. It should be simple "bean" or "POJO" class typically composed of some private properties and public getters and setters (aka accessors and mutators). Your List of Cars will be composed of these objects.
public class Car {
private String carID;
...
private Integer quantity;
public getCarID() {
return this.carID;
}
...
public setQuantity(Integer quantity) {
this.quantity=quantity;
}
}
Define your list of Cars as a property of your current class, and each time you add a Car to your list, construct it from your Car class.
Car car=new Car();
car.setCarID(st.nextToken());
...
car.setQuantity(Integer.valueOf(st.nextToken()));
this.carList.add(car);
Related
I have a CarModel class that has three fields: name, fuelEconomy, and gasTankSize.
class CarModel {
private String name;
private double fuelEconomy;
private double gasTankSize;
CarModel(String name, double fuelEconomy, double gasTankSize) {
this.name = name;
this.fuelEconomy = fuelEconomy;
this.gasTankSize = gasTankSize;
}
String getName() {
return name;
}
double getFuelEconomy() {
return fuelEconomy;
}
double getGasTankSize() {
return gasTankSize;
}
}
Given the input as a string of text separated by a new line:
MODEL Camry 6.5 58
MODEL Civic 7.5 52
FINISH
How can I create a new object every time the word MODEL is in the input, store the model in an array, use the following words as the data for those fields and end the program when FINISH is in the input?
Inside main method, try doing something like this (Using try with resources):
public static void main(String args[]){
String line;
List<CarModel> cars = new ArrayList<>();
try(Scanner sc = new Scanner(System.in)){
while(sc.hasNextLine()){
line = sc.nextLine();
String[] arr = line.split(" ");
if(arr[0].equalsIgnoreCase("Model")){
cars.add(new CarModel(arr[0], Double.parseDouble(arr[1]), Double.parseDouble(arr[2])));
}else if(arr[0].equalsIgnoreCase("Finish"){
break;
}
}
}catch(ArrayIndexOutOfBoundsException ex){
// do something here!
}catch(Exception ex){
// do something here as well!
}
}
I would use the String.split method. You pass a delimiter, in your case a space character, and then the method chops the string into pieces based on your provided delimeter. Getting the input into your program depends on where the input will be coming from, whether by file or terminal or some other source.
Once you've read a line of input, call String[] values = line.split(" ")
Again, how to read the input depends on where the input is coming from, which you haven't specified.
I want to asign data, that I previously read from a simple "backup" text file (txt), to n differentiable instances of a class so that I can use those instances later on. Is there a way to achieve this using some kind of loop?
I tried creating multiple instances c_0, c_1, .. , c_n of a class "Category" which store the "category name" from the corresponding line in a txt file. A line from that file starts with the category name followed by a comma and negligible information. Now I want to have n (= amount of lines) different Category instances every time I call this function in the beginning of the script. Up till now I tried the following:
public class Backup{
static int maxC = 0;
public static void main(String[] args) throws IOException{
readC();
}
public static class Category{
private String categoryName;
public Category(String nameC){
categoryName = nameC;
}
}
private static void readC(){
BufferedReader br = null;
String line = "";
String seperate = ",";
int i = 0;
try{
br = new BufferedReader(new FileReader("C:/Users/Public/Category.txt"));
while((line = br.readLine()) != null){
String[] oneLineArray = line.split(seperate);
Category c_i = new Category(oneLineArray[0]); //I have a strong feeling
//that this only creates c_i and not the c_0 c_1 that I would want here
//How can one achieve that?
i++;
}
}catch(FileNotFoundException e){
System.out.println("File does not exist. "+e.getMessage());
}catch(IOException e){
System.out.println("I/O Error. "+e.getMessage());
}finally{
if (br != null){
try{
br.close();
}catch(IOException e){
System.out.println("I/O Error. "+e.getMessage());
}
}
}
maxC = i-1; //this is the amount (n) of instances created
}
}
Like I said, I expected to have multiple instances but i kinda suspect every cycle of the loop is just c_i and not c_0 etc. Can someone enlighten me? Where did I go wrong?
c_i is just the variable name, i there is just a character like c or _.
You want to create either an array or a collection. java.util.ArrayList collection is the easiest choice, it will store all new objects and dynamical adjust size.
List<Category> categories = new ArrayList<>();
while((line = br.readLine()) != null){
String[] oneLineArray = line.split(seperate);
Category c = new Category(oneLineArray[0]);
categories.add(c);
}
I have been tasked with creating a game called Taboo. It consists of a main word and 3 banned words. The aim of the game is for the words to display on the screen and the user then has to describe the main word without using the word itself or the banned words.
I have so far been able to read in the data that I have stored in a CSV and have it so that when I choose to output BannedWords, it does so. The problem now, is that when it outputs either MainWord or BannedWord1, etc... it outputs the data for each record in the CSV.
Below is the data from my CSV (it is just a test with few records so that when it works I can introduce the rest).
Tree,Brown,Green,Nature
Lake,Blue,Water,Wet
Apple,Green,Fruit,Healthy
If I chose to output MainWord, which is the first word, it outputs like this:
Tree
Lake
Apple
I need to somehow store the data being read in from the CSV individually in a collection so that when I need to use them, they output properly and they in a such a way that I can display them later on in a GUI JLabel.
It might also be useful to note that I am using NetBeans so I am able to use any of the built in functions as well.
public class Card
{
private String sMainWord;
private String sBannedWord1;
private String sBannedWord2;
private String sBannedWord3;
public Card(String sMW, String sBW1, String sBW2,String sBW3)
{
sMainWord = sMW;
sBannedWord1 = sBW1;
sBannedWord2 = sBW2;
sBannedWord3 = sBW3;
}
public void setsMainWord(String sMW)
{
sMainWord = sMW;
}
public String getsMainWord()
{
return sMainWord;
}
public void setsBannedWord1(String sBW1)
{
sBannedWord1 = sBW1;
}
public String getsBannedWord1()
{
return sBannedWord1;
}
public void setsBannedWord2(String sBW2)
{
sBannedWord2 = sBW2;
}
public String getsBannedWord2()
{
return sBannedWord2;
}
public void setsBannedWord3(String sBW3)
{
sBannedWord3 = sBW3;
}
public String getsBannedWord3()
{
return sBannedWord3;
}
public static void main(String[] args) throws FileNotFoundException
{
String fileNameDefined = "/Users/student/NetBeansProjects/TabooGameComplete/CSData.csv";
File file = new File(fileNameDefined);
try
{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext() != false)
{
String TabooCardWords = inputStream.nextLine();
String[] information = TabooCardWords.split(",");
String MainWord = information[0];
String BannedWord1 = information[1];
String BannedWord2 = information[2];
String BannedWord3 = information[3];
Card TBC = new Card (MainWord, BannedWord1, BannedWord2, BannedWord3);
System.out.println("*" + BannedWord1 + "*");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You are executing the output statement in the loop that generates your Cards so that everytime a card is created, you are outputting its BannedWord1. As you are creating them all, one after another, they will all output, one after another.
i.e.
//For each line in file
while(inputStream.hasNext() != false)
{
//Create Card
//Output BannedWord1 used to create Card
}
If you want to output one element of one Card, you will need to keep the Card objects you create to be used outside the loop:-
Card[] cards = new Cards[3];
int i=0;
//For each line in file
while(inputStream.hasNext() != false)
{
//Create Card
cards[i++] = newlyCreatedCardObject; //Store card object for later
//Output BannedWord1 used to create Card
}
//Output BannedWord1 from the Card created from the second line
System.out.println(cards[1].getsBannedWord1());
Additional Point
By convention, java variables begin with lowercase letters and classes with uppercase, so this can be confusing
String TabooCardWords; //Should really be 'tabooCardWords'
...
String MainWord = information[0]; //-> 'mainWord'
String BannedWord1 = information[1]; //-> 'bannedWord1'
String BannedWord2 = information[2]; //-> 'bannedWord2'
String BannedWord3 = information[3]; //-> 'bannedWord3'
I am trying to complete a little program.
I've got a text file (.txt) to store different data on objects that i've got.
The structure of the file is the next (exemples data.txt) :
Sedane
2005
195000
Diesel
Blue
SUV
2013
34000
Fuel
Black
Each object is made true a class that i've build called Cars.
So the 1 line is the type of car, the 2nd the year of built, the 3rd line is the milage, the 4th is the type of fuel, and the 5th line is the color of the car.
So basicly i need to open the file, and load the data into the memory when i execute my program into an array with object in it.
I'm ok to open the file but i'm blocked when it comes to reading the data and putting it in an array.
The array size is 2 for this exemple, but if i have more entries in the file it's going to adapt it's size when loading at the startup of the program.
Here's what i've got unti now (for my code ...)
public static void loadCars () {
FileReader fopen;
BufferedReader opened;
String line;
try {
fEntree = new FileReader( "data.txt" );
opened = new BufferedReader( fopen );
while ( opened.ready() ) {
line = opened.readLine();
// Don't know what to do here ????
}
opened.close();
} catch ( IOException e ) {
System.out.println( "File doesn't exist !" );
}
}
Someting like this will do the trick. I'm adding the file contents line by line to an Arraylist instead of an array though. This way you don't have to know how big your array needs to be before hand. Plus you can always change it to an array later.
public ArrayList<String> readFileToMemory(String filepath)
{
in = new BufferedReader(new FileReader( "data.txt" ));
String currentLine = null;
ArrayList<String> fileContents = new ArrayList<String>();
try
{
while((currentLine = in.readLine()) != null)
{
fileContents.add(currentLine);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
return fileContents;
}
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
long length = lnr.getLineNumber();
lnr.close();
in = new BufferedReader(new FileReader( "data.txt" ));
Car[] cars= new Car[length/5];
String currentLine;
int i=0;
for(int i=0;i<length/5;i+=5) {
String name = in.readLine();
String year = in.readLine();
String miles = in.readLine();
String gas = in.readLine();
String color = in.readLine();
cars[i] = new Car(name,year,miles,gas,color);
}
You'll have to handle exceptions too, surround stuff in try catch structures.
You can look at my solution here below (I also corrected/simplified some problems with the variables for reading the file, anyway this was not the main topic):
public static void loadCars() {
FileReader fopen;
BufferedReader opened;
String line;
ArrayList<Car> carList = new ArrayList<Car>();
try {
fopen = new FileReader("data.txt");
opened = new BufferedReader(fopen);
int nFields = 5; // we have 5 fields in the Car class
String[] fields = new String[nFields]; // to temporary store fields values read line by line
int lineCounter = 0;
while ((line = opened.readLine()) != null) {
fields[lineCounter] = line;
lineCounter++;
if ((lineCounter) % nFields == 0) { //it means we have all 5 fields values for a car
carList.add(new Car(fields)); //therefore we create a new car and we add it to the list of cars
}
}
opened.close();
} catch (IOException e) {
System.out.println("File doesn't exist !");
}
}
Basically we use an ArrayList to store all the cars, and we read the file, waiting to have all the fields values in order to create the Car object. I store the fields values in an array of Strings: I don't know how you implemented the Car class, but maybe it is useful to create a constructor that takes as parameter an array of strings, so it can set the fields, for instance:
class Car {
private String type;
private String year;
private String milage;
private String fuel;
private String color;
public Car(String[] fields) {
type=fields[0];
year=fields[0];
milage=fields[0];
fuel=fields[0];
type=fields[0];
}
}
But I've to say that probably this is a little 'too static'.
For simplicity I assumed that all your fields are of String type, but probably fields like 'year' or 'milage' might be of int type. In this case you can use array of Object[] (instead of String[]), and then cast the value with the right type.
I hope this may help you.
The code I have produced is meant to provide functionality of reading a text file line by line, saving each line into an array. It seems to read in each line correctly but when I use the printProps() method it only displays one...
Code is only saving one line of a text file to the array, what's wrong with my code?
/*reading in each line of text from text file and passing it to the processProperty() method.*/
Public void readProperties(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
int i = 0;
String line;
line = reader.readLine();
while (line != null && !line.equals("")) {
i++;
processProperty(line);
line = reader.readLine();
}
System.out.println("" + i + " properties read");
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
/*Breaks up the line of text in order to save the value to an array (at this point it only saves one line to the array). org.newProp(newProp) passes the new property to the Organize class where it saves it to an array.
public void processProperty(String line) {
org = new Organize();
int id = nextPropertyID;
nextPropertyID++;
String[] parts = line.split(":");
int propNo = Integer.parseInt(parts[0]);
String postcode = parts[1];
String type = parts[2];
int bedrooms = Integer.parseInt(parts[3]);
int year = Integer.parseInt(parts[4]);
int rental = Integer.parseInt(parts[5]);
Landlord landlord = theLandlord;
Tenant tenant = null;
org.propUniqueCheck(id);
propNoCheck(propNo, postcode);
postcodeCheck(postcode,propNo);
typeCheck(postcode, propNo, type);
bedroomsCheck(bedrooms, postcode, propNo);
yearCheck(propNo, postcode, year);
System.out.println("Creating property " + id);
Property newProp = new Property(id, propNo, postcode, type, bedrooms, year,
rental, landlord, tenant);
org.newProp(newProp);
org.printProps();
}
/*From here down it is the code to save the value to the array*/
public Organize() {
props = new ArrayList<Property>();
PTs = new ArrayList<PotentialTenant>();
waitingList = new LinkedList<String>();
//myList.add(new prop(Property.toString()));
}
public void newProp(Property p)
{
props.add(p);
}
I have actively been seeking help in my seminar with this problem and I can't seem to find a solution, any advice would be very much appreciated!
In processProperty you are instantiating a new Organize object. Therefore, each Property (which you create for each row) is ending up in a different ArrayList (as the first element).
One solution would be to instantiate one Organize object before you start your loop and then pass this into your processProperty method as a parameter.
When one line in your text file is an empty String, your while-loop will break.
This is the right way to implement the loop:
String line = "";
while ((line = reader.readLine()) != null) {
// your code here
}
In processProperty you are instantiating a new Organize object. Therefore, each Property (which you create for each row) is ending up in a different ArrayList (as the first element).
One solution would be to instantiate one Organize object before you start your loop and then pass this into your processProperty method as a parameter.
String line = "";
while ((line = reader.readLine()) != null) {
// your code here
}