Adding data to arrayList Java - java

So I'm creating a logging program where a user enters the KM's and it saves it etc.
I take in four variables - start KM, end KM, start and end location. I'm new to java so I'm just wondering if anyone can confirm if theres a better way to do this. This is my code so far, I want to save it to an array of sorts (to a list??) so I can access each object i.e. the startKM, but they need to be on the same line, as in object 1 of array etc. and then write to file,
What I was thinking of doing was saving that linked list to a file, and adding a ; in the toString method and when reading the file in just breaking it at the ; Is there a better way to do this?? Thanks guys. the data is assigned from whatever the user enters in the text fields.
double startKM;
double endKM;
String startLocation;
String endLocation;
startKM = Double.parseDouble(txtStartKM.getText());
endKM = Double.parseDouble(txtEndKM.getText());
startLocation = txtStartLocation.getText();
endLocation = txtEndLocation.getText();
details.startKM = startKM;
details.endKM = endKM;
details.startLocation = startLocation;
details.endLocation = endLocation;
//List<DrivingDetails> detailsList = new ArrayList<DrivingDetails>();
List detailsList = new ArrayList();
detailsList.add(details);
System.out.println("LinkedList contains = \t " + detailsList.toString());
edit: I have another class (DrivingDetails) which holds the following variables:
public class DrivingDetails {
double startKM;
double endKM;
String startLocation;
String endLocation;
}

Your DrivingDetails class violates the principle of encapsulation for object oriented classes. I would add setters and getters for all properties. Also, you could create a contstructor that handles initialization for you.
public class DrivingDetails {
private double startKM;
private double endKM;
private String startLocation;
private String endLocation;
public DrivingDetails(double startKM, double endKM, String startLocation, String endLocation) {
this.startKM = startKM;
this.endKM = endKM;
this.startLocation = startLocation;
this.endLocation = endLocation;
}
public double getStartKM() {
return startKM;
}
public void setStartKM(double startKM) {
this.startKM = startKM;
}
// rest of the methods left for you ...
}
Your resulting code would then look like:
double startKM;
double endKM;
try {
startKM = Double.parseDouble(txtStartKM.getText());
endKM = Double.parseDouble(txtEndKM.getText());
} catch (NumberFormatException e | NullPointerException e) {
// the line above assumes java 7
// recover
}
DrivingDetails details = new DrivingDetails(startKM, endKM,
txtStartLocation.getText(),
txtEndLocation.getText());
List<DrivingDetails> detailsList = new ArrayList<DrivingDetails>();
detailsList.add(details);
Hope that helps!

Related

Java Extracting values from text files and put it into a array type class Forfait

Im new in java hope y'all doing great.
So i was trying to extract values from my text files and put into the array named tableauForfaits but i'm blocked can someone help me to see where's my error because when i try to split it doesn't work.
private static final String FIC_FORFAITS = "Forfaits.txt";
// Déclaration des variables
private static Forfait tableauForfaits[] = new Forfait[6];
* Read data from different packages (id | description | price)
* in the "Forfaits.txt" file. The first line in this file is the
* description of other lines and it should be ignored when
* reading. The other lines of this file are each composed of the identifier,
* of the description, and the price separated from each other by a vertical bar.
* Each of these lines must be read and cut to create an object of type
* Package, and this item should be added in the package table above
* defined (see Forfaits.txt file for more details)
*
public static void lireFichierForfaits() throws IOException,FileNotFoundException {
try (BufferedReader reader = new BufferedReader (new FileReader(FIC_FORFAITS))) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
tableauForfaits = line.split("\\|");
for (String part : tableauForfaits) {
System.out.println(part);
}
System.out.println();
}
reader.close();
}
}
/ The Class Forfait :
private String identifiant;
private String description;
private float prix;
public Forfait (String identifiant, String description, float prix) {
this.identifiant = identifiant;
this.description = description;
this.prix = prix;
}
public String getIdentifiant () {
return identifiant;
}
public void setIdentifiant (String identifiant) {
this.identifiant = identifiant;
}
public String getDescription () {
return description;
}
public void setDescription (String description) {
this.description = description;
}
public float getPrix () {
return prix;
}
public void setPrix (float prix) {
this.prix = prix;
}
This:
tableauForfaits = line.split("\\|");
won't work because String#split(...) returns an array of String, and you're trying to force this into an array of a different type, a Forfait object.
Instead, that line should be
String[] tokens = line.split("\\|");
This will hopefully split the row from the text file into individual small String tokens that can be used to help you create a single Forfait object with the tokens. How you create the object completely depends on the structure of this class (one that we are currently unable to see), but you likely need to call its constructor, using the String tokens obtained, and then put the Forfaitobject created into the tableauForfaits array, perhaps something like,
Forfait forfait = new Forfait(token[0], token[1].....);
Note that you may need to parse numeric token Strings to a numeric value before doing this, such as
Forfait forfait = new Forfait(Integer.parseInt(token[0]), token[1], .....);
Again, it's impossible to say for sure, since we currently cannot see the Forfait class or the text file.
You will also need to create an int index variable before the while loop, increment it within the while loop, and use this as an index to the tableauForfaits array to help you decide which row of the array to put your newly create object into.

How do I store values from a method parameter into an array?

I am writing a program to store certain Recipe info. into an array. Using method RecipeEntry(), with its parameters, the program is meant to store up to a maximum of 3 recipes into an array named: totalEntry[].
Below is my attempt at writing this program, however, I am getting errors .. unable to figure out what it is that I am missing.
import java.util.*;
public class RecipeArray
{
private String author;
private Recipe recpH_1;
private Recipe recpC_2;
private static RecipeEntry[] totalEntry = new RecipeEntry[3];
private static int entryCount;
public RecipeArray(String author, Recipe hot, Recipe cold) // constructor
{
entryCount = 0;
this.author = author;
recpH_1 = hot;
recpC_2 = cold;
totalEntry[entryCount] = new RecipeArray(author, recpH_1, recpC_2);
}
public static void main(String[] args)
{
RecipeEntry("Mary Bush", SpaghettiHOT, SpaghettiCOLD);
// RecipeEntry method, when called should pass its parameter values into
// totalEntry [] array. entryCount variable should keep count of every entry.
System.out.println("ALL ENTRY = " + entryCount + Arrays.toString(totalEntry));
}
}
public class Recipe //create class data of type recipe
{
private String name;
private int id, rating;
public Recipe(String name)
{
this.name = name;
id = 0;
rating = 0;
}
}
The expected output should print a list of the entries - Example:
Output:
index 0 - [Mary Bush, SpaghettiHOT{id=0, rating=0}, SpaghettiCOLD{id=0, rating=0}]
The problem is that you didn't catch the returned Array from your method:
RecipeEntry("Mary Bush", SpaghettiHOT, SpaghettiCOLD);
Actually the RecipeArray as you wrote will return an Array; it means that the method will pass and Array to it's caller.
Changing the mentioned line with the following line will solve the problem:
RecipeEntry[] totalEntry = RecipeEntry("Mary Bush", SpaghettiHOT, SpaghettiCOLD);
Visit https://www.tutorialspoint.com/importance-of-return-type-in-java for better understanding of Java Methods:

How do I access an array within an array?

Say I have a .txt file that has information being split by a comma as such:
IN,Indiana,6634007
While this is a snippet which accesses that file and splits it:
for(int i=0; i < count; i++) {
line = bufferedReader2.readLine();
String space[] = line.split(",");
String abb = space[0];
String nme = space[1];
int pop = Integer.parseInt(space[2]);
states[i] = new State(abb, nme, pop);
}
The purpose of that was so that all the information in the txt file could be accessed, so for example this code would print exactly whats present on the .txt file:
System.out.println(states[0]);
would print:
IN,Indiana,6634007
My question is, how would I have it so that I can access the specific part of the array as in how would I print lets say just the name "Indiana" or the population "6634007"?
P.S I'm sorry if the title of my question did not make sense, I did not exactly know how to word it.
Somewhere, you have a class called State. states is an Array of this class. So you can add a getter to State:
public int getPop() {
return pop;
}
And call it on your Object like this:
System.out.println(states[0].getPop());
as states[0] is simply a State object.
Add more getters to access different fields.
if you just want to print every single line, you can try this like below:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = null;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null ) {
list.add(line);
}
System.out.println(list.get(0));
// TODO realease resources
}
From your question what i can realise is, you are using State class to store the information. In such case, check the state class where the first parameter value is stored. Later to print the corresponding information, access its object variable as SapuSeven mentioned.
For eg.
public class State{
public String a;
public String b;
public int c;
public State(String x, String y, int z){
a=x;
b=y;
c=z;
}
}
now u can access like
System.out.println(states[0].b);
for printing the name of city
OR
you can simply print the value using index like this
System.out.println(states[0].split(",")[2]);

If a constructors value is null, can I give it a default?

I am using a recycler view to display data on my app. When I want to get the information from an API that I am using I am taking in 14 different variables.
for(int i = 0; i<array.length();i++){
JSONObject object = array.getJSONObject(i);
//object.getJSONObject("test");
Personnel personnel = new Personnel(
object.getInt("contactType"),
object.getString("currentTime"),
object.getString("clockIn"),
object.getString("clockOut"),
object.getInt("isClockedIn"),
object.getString("clockInPhotoName"),
object.getDouble("clockInLat"),
object.getDouble("clockInLng"),
object.getDouble("clockOutLat"),
object.getDouble("clockOutLng"),
object.getDouble("projectSiteLat"),
object.getDouble("projectSiteLng"),
object.getDouble("clockInDistanceFromProjectSiteInMetres"),
object.getDouble("clockOutDistanceFromProjectSiteInMetres")
);
personnelList.add(personnel);
}
But in my response body from my http call, some times for example, the object that is calling "isClockedIn", may be empty, and if I do this, then my constructor wont make an object.
This is my very long constructor:
public Personnel(int contactType, String totalTimeSummary, String clockInTime, String clockOutTime, int isClockedIn, String clockInPhotoName, double clockInLat, double clockInLong, double clockOutLat, double clockOutLong, double projectLat, double projectLong, double clockInDistance, double clockOutDistance) {
this.contactType = contactType;
this.totalTimeSummary = totalTimeSummary;
this.clockInTime = clockInTime;
this.clockOutTime = clockOutTime;
this.isClockedIn = isClockedIn;
this.clockInPhotoName = clockInPhotoName;
this.clockInLat = clockInLat;
this.clockInLong = clockInLong;
this.clockOutLat = clockOutLat;
this.clockOutLong = clockOutLong;
this.projectLat = projectLat;
this.projectLong = projectLong;
this.clockInDistance = clockInDistance;
this.clockOutDistance = clockOutDistance;
}
I was looking around and saw that you can just make a default constructor if my other constructor doesn't fill all the needed variables, but of course I dont want to do this because then all of the parameters will be empty.
Cheers.
Instead of calling getDouble, you can use optDouble. The first value should be the key you're already using, the second value should be the value that will be used whenever the key is not found from the server response.
You can find some real world examples here: https://www.programcreek.com/java-api-examples/?class=org.json.JSONObject&method=optDouble
You should not use primitive variables. For example, int can't be null, On the other hand integer type can be null. Take a look at this link
As GhostCat suggested, you should really consider builder pattern, example:
public Personnel {
public static class Builder {
int contactType;
//all the other members
public Builder contactType(int contactType) {
this.contactType = contactType;
return this;
}
public Personnel build() {
Personnel personnel = new Personnel();
personnel.contactType = this.contactType;
}
}
int contactType;
//all the other members
private Personnel() {}
// getters and setters
}
Personnel personnel = new Personnel.Builder()
.contactType(0)
.build();

How do I split a string, convert to double, and output a string again? Java! (Code not working)

I am a beginner java coder on an assignment. Please don't report as too vague/duplicate etc, I really need help tailored to me as I have looked at many other answers and just dont understand whats going on!
This bit of code is where my string - e.g. 5x^3 + 2x^2 will be input
String P = Polynomial;
Expression poly = new Variable(P);
Expression diffpoly = poly.derive();
Here is my code where I need the help:
public class Variable implements Expression
{
private double coeff1, power1,newcoeff,newpow;
private String stringpoly;
//public Variable(String[] t)
public Variable(String p)
{
stringpoly = p;
}
public Expression derive()
{
String[] parts;
parts = stringpoly.split("x");
coeff1 = double.parseDouble(parts[0]);
power1 = double.parseDouble(parts[1]);
newcoeff = coeff*power1;
newpower = power1-1;
String newcoeffstr = Double.toString(newcoeff);
String newpowerstr = Double.toString(newpower);
String differentiatedterm = newcoeffstr + "x^" + newpowerstr;
return new Variable(differentiatedterm);
}
public double evaluate(double a)
{
return stringpoly;
}
public String toString()
{
return Double.toString(stringpoly);
}
}
So my issue, is that I am getting errors saying
errors
Can anyone explain these errors for me?
double is a primitive datatype in java. It does not represent an object or a class.
To call methods an object or at least a class is required.
Check the documentations for primitive types here
Check the different wrapper classes and how to use them here
You will have to use the double's wrapper class Double to be able to call the function parseDouble(...)
double parsedNumber = Double.parseDouble("1083407810329");

Categories