Converting Enum to a String Object for Java seamlessly - java

I am shaky with parsing and handling text files. How do I convert my method signatures with enums to strings so I can read from a text file and parse effectively without wasting CPU resources? I currently have method signatures like this
public void createReservation(VehicleType v, String cName, long phoneNumber, String sDate, String eDate) throws Exception //right here
{
//trouble with representing VehicleType v in my Reservation text file
}
Reservation.txt file looks like this matching the signature Above
"COMPACT", "John Wick", 312 900 6001, "2019-02-09", "2019-02-14"
"SUV", "Harvey Dent", 302 600 2001, "2019-02-11", "2019-02-15"
In my main class I have a parseVehicleLine method like this..
private void parseReservationLine(String str){
Scanner sc = new Scanner(str);
sc.useDelimiter(",");
while(sc.hasNext()){
vehicleType = sc.next();//there is an error here because it is still an enum of Vehicle class
String cName = sc.next();
long phoneNumber = sc.nextLong();
String Date = sc.next();
String eDate = sc.next();
}
sc.close();
}
public abstract class Vehicle {
public enum VehicleType
{
ECONOMY(18.00), PREMIUM(22.50), SUV(25.50);
private double vehicleDailyCost;
private VehicleType(double vehicleDailyCost)
{
this.vehicleDailyCost = vehicleDailyCost;
}
public double getVehicleDailyCost()
{
return vehicleDailyCost;
}
}
Can someone explain how I could properly convert the VehicleType enum to a String without issues? Thanks!

You are reading the text file as String, so I think you need to convert String to VehicleType, not vice-versa as you mentioned.
You should be able to get enum from String using valueOf():
vehicleType = VehicleType.valueOf(sc.next());

Related

How to access and read the values of child objects of an object?

Here is how I am constructing an Object inside a method:
//right after creating the class
public static ArrayList<Object> old_devicelist = new ArrayList<Object>();
//inside a method
Date date = new Date();
long time = date.getTime();
Integer opened = 0;
String deviceId = "";
String dev_rssi = "";
Object[] MyObject = new Object[]{time, opened, deviceId, dev_rssi};
old_devicelist.add(MyObject);
Now, I would like to loop through that ArrayList and access some elements (note that deviceId might at some point contain an object and I would like to access id field of it) inside it, then I would like to use them like this, for ex. :
if(device.id == 33){
//do something...
}
You're using an array with type Object and then you're storing these object arrays into a list. This makes it hard to retrieve the information later.
Consider this instead:
public static List<Device> DEVICES = new ArrayList<>();
class Device {
Date date;
long time;
Integer opened;
String deviceId;
String deviceRssi
Device(Date date, Integer opened, String deviceId, String deviceRssi) {
this.date = date;
this.time = date.getTime();
this.opened = opened;
this.deviceId = deviceId;
this.deviceRssi = deviceRssi;
}
}
Device first = new Device(
new Date(),
0,
"",
"");
DEVICES.add(first);
System.out.println(DEVICES.get(0).deviceId);
...
for (Device device : DEVICES) {
if (device.deviceId.equals("33)) {
// ...
}
}
I'd recommend not using too many static/global variables and reading about the Java Naming Convention.
I guess you should create new class instead of using Object.
public class DeviceSpecification { //or any other name
long time;
Integer opened;
String deviceId;
String dev_rssi;
public DeviceSpecification(long time, Integer opened, String deviceId, String dev_rssi) {
this.time = time;
this.opened = opened;
this.deviceId = deviceId;
this.dev_rssi = dev_rssi;
}
}
Create a list with specific type:
public static List<DeviceSpecification> oldDeviceCollection = new ArrayList<>();
Create an instance of a class
DeviceSpecification device = new DeviceSpecification(new Date().getTime(), 0, "", "")
Add the instance to a list
oldDeviceCollection.add(device);
Use it in query - we can use streams from Java 8
oldDeviceCollection.stream()
.forEach(
device -> {
if(device.id.equals("33")) {
// do something
}
);
First of all your Arraylist takes Objects and you are trying to add an Object array so if your goal is to keep object arrays with the device_id you should change your Arraylist to
public static ArrayList<Object[]> old_devicelist = new ArrayList();
Taking that in mind you can access any deviceid by typing
old_devicelist.get(i)[2]
where i is the element you want and 2 because you have setted device_id to be the 3rd element of your Object array!
Hope this helps!

Is there a way loop through 2 arrays and print the element of array 1 if it contains the substring of any element from array 2?

The problem I am trying to solve is how to read lines from a text file and add it to an array. Then sort each element from this new array by the date that is also in each element. I will explain so its easier to understand but will explain what I am doing.
My text file (First column is name, second is Date of birth and last is the date the person died):
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
john smith,1967-03-04,2017-04-04
I want to sort this file and output it to another file (testing by printing to console at the moment) by sorting it by the date the person died. A way I thought of doing this is to read each line and pass it to an array. Then read each element within the array, split it and then save the date the person died to another array. Then sort the array that has the death dates, loop through both arrays by seeing if the first element of the death date array matches the first element of the first line in the text file, if so then write it to another file. If not then go to the next line.
For example
BufferedReader reader = new BufferedReader(new FileReader("input_text.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("output.txt",true));
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> substr_date = new ArrayList<String>();
String currentline = reader.readLine();
while(currentline !=null){
String a_line[] = currentline.split(",");
substr_date.add(a_line[2])
lines.add(currentline);
currentline = reader.readLine();
}
Collections.sort(substr_date);
for(String date : substr_date){
for(String line : lines){
if(line.contains(date)){
System.out.println(line);
}
}
}
I expect the output to be:
john smith,1967-03-04,2017-04-04
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
The results are initially in order but then some lines are repeated multiple times and then the whole text file in repeated to the console and becomes a mess. I am not sure how to go about doing this. I am new to java and not sure if I asked this question properly either so if you need any more info please ask.
I would create class for objects which you can insert into a list and then define a comparator on this class which you can use to sort.
Here is an example of the class you could define:
static class DeceasedPerson {
String name;
LocalDate birthDate;
LocalDate deathDate;
DeceasedPerson(String name, LocalDate birthDate, LocalDate deathDate) {
this.name = name;
this.birthDate = birthDate;
this.deathDate = deathDate;
}
#Override
public String toString() {
return name + ", " + birthDate + ", " + deathDate;
}
}
Then you could simply load objects based on this class into a list which you sort using a comparator. Here is some sample code you can run with the class defined above:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
List<DeceasedPerson> deceasedPersonList = new ArrayList<>();
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.sort(Comparator.comparing(o -> o.deathDate));
deceasedPersonList.forEach(System.out::println);
}
If you run the code above using the DeceasedPerson class you should see on the console the following output:
john smith, 1967-03-04, 2017-04-04
sarah jones, 1966-12-02, 2018-12-04
matt smith, 1983-02-03, 2020-03-02
You could actually also use a TreeSet instead of a List in the main method above and achieve the same results. Here is a move concise alternative:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
Set<DeceasedPerson> deceasedPersonList = new TreeSet<>(Comparator.comparing(o -> o.deathDate));
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.forEach(System.out::println);
}
The way you are doing is a long shot. You can do this in much simpler way. You could pass a comparator to the Collections.sort() method like this.
Collections.sort(substr_date, new Comparator<String>{
#Override
public int compare(String str1, String str2){
String dd1 = str1.split(",")[2];
String dd2 = str2.split(",")[2];
return dd1.compareTo(dd2);
}
});
Comparing dates like this, though, is not a good approach. You should convert the date string to LocalDateTime and then use isBefore() or isAfter() to compare them. For ex,
public int compare(String str1, String str2){
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd")
LocalDateTime d1 = LocalDateTime.parse(str1.split(",")[2],format);
LocalDateTime d2 = LocalDateTime.parse(str2.split(",")[2],format);
return d1.isBefore(d2)?-1:(d1.isAfter(d2)?1:0);
}

Parsing CSV file with #Parsed annotation in a Form - Univocity parser

I am trying to parse a CSV file with some #Parsed annotation in a form file but it's not working.
I am using univocity lib
Init.java
public static void main(String[] args) throws FileNotFoundException {
CsvParserSettings parserSettings = new CsvParserSettings();
BeanListProcessor<FireReportFormGeneral> rowProcessor = new BeanListProcessor<FireReportFormGeneral>(FireReportFormGeneral.class);
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(parserSettings);
parser.parse(new FileReader("/home/jose/Desktop/example.csv"));
List<FireReportFormGeneral> beans = rowProcessor.getBeans();
System.out.println(rowProcessor.getHeaders());
System.out.println(beans);
}
FireReportFormGeneral.java
#Parsed(field = "Account Number")
private String accountNumber;
#Parsed(field = "Account Type")
private String accountType;
#Parsed(field = "Bank Client Identification Number")
private String bankClientIdNumber;
#Parsed(field = "Account Opening Date")
private String accountOpeningDate;
//getters and setters
But my output is always something like:
[Ljava.lang.String;#7591083d
[com.opessoftware.fire.csv.reader.FireReportFormGeneral#77a567e1,
com.opessoftware.fire.csv.reader.FireReportFormGeneral#736e9adb]
For sure I am doing something wrong but I could not find the answer.
Thanks.
EDIT:
I solve the problem
The thing is if a call beans.get(index).getAccountName() for example it's going to return values for me.
You could add a toString() method to FireReportFormGeneral.java, then your System.out.println() should be more readable.
eg.
public String toString(){
return "Account number: " + accountNumber + " Account Type: " + accountType;
}
This is just a simple example, without null checks, StringBuilder etc...
Does this solve your problem?

Read data from a text file and create an object

I need some help:
I'm making a Supermarket simulation on Java, but I've got one problem, I have a text file (Stock.txt) where I have all the supermarket stock on it for example:
0-Bakery-Chocolate Cake-$12.5-250
1-Meat-Premium Steak-$2.6-120
2-Seafood-Tuna - $1.2-14
...
Where the first number is the "id" for the product, next is the department the product belongs, third is the name of the product, the next thing is the price, and the last number is how much pieces of the product the stock has.
I have this class:
public class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
}
So, basically what I need to do is to read each line from the text file and create the product, i.e. for the first line make something like this:
Product product1 = new Product(0,"Bakery","Chocolate Cake", 12.5, 250);
And then add it to an array
Product[0] = product1;
For all the things that are in the text file, then, when running the simulation each costumer will buy a random quantity of random products in stock, so the stock number will decrease. Finally, when the simulation ends, the program must write in the same text file, the modify quantity of each product.
The thing is that maybe it's too easy to do but I have no idea of how to do this, because reading and writing a file in Java has been a real problem for me since I started programming in Java (I'm a beginner).
I have some ideas of using the BufferedReader and the StringTokenizer classes for the reading and creating the object problems, but I can't figure it out how to do it, and I have no idea of how must I do the overwritting problem.
I'd really appreciate your help!
Oh! By the way, I really need to use only the arrays, so using an ArrayList or any other structure it's not even a choice :(
This is a good job for a Scanner to read in the data. As far as not being able to use collections like ArrayList you'll have to dynamically reallocate an array yourself.
Try the following:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("Stock.txt"));
input.useDelimiter("-|\n");
Product[] products = new Product[0];
while(input.hasNext()) {
int id = input.nextInt();
String department = input.next();
String name = input.next();
double price = Double.valueOf(input.next().substring(1));
int stock = input.nextInt();
Product newProduct = new Product(name, price, department, id, stock);
products = addProduct(products, newProduct);
}
for (Product product : products) {
System.out.println(product);
}
}
private static Product[] addProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProducts;
}
public static class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
private static NumberFormat formatter = new DecimalFormat("#0.00");
public Product(String n, double p, String d, int i, int s) {
name = n;
price = p;
department = d;
id = i;
stock = s;
}
#Override
public String toString() {
return String.format("ID: %d\r\nDepartment: %s\r\nName: %s\r\nPrice: %s\r\nStock: %d\r\n",
id, department, name, formatter.format(price), stock);
}
}
Results:
ID: 0
Department: Bakery
Name: Chocolate Cake
Price: 12.50
Stock: 250
ID: 1
Department: Meat
Name: Premium Steak
Price: 2.60
Stock: 120
ID: 2
Department: Seafood
Name: Tuna
Price: 1.20
Stock: 14
For simplicity, I have defined all the items as String.
Product DAO:
public class Product {
private String name;
private String price;
private String department;
private String id;
private String stock;
//generate `enter code here`
//getters & setters
//toString
Put your product list in "testData/product.txt". This is assuming that your list of products comes in same format, i.e. id-department-name-price-stock \n.
Use the jUnit test below to test your code. You can certainly modify how you read the product.txt file (may be other powerful string readers).
#Test
public void test() {
try {
List<String> productLines = Files.readAllLines(java.nio.file.Paths.get("./testData/product.txt"), StandardCharsets.UTF_8);
for (String line: productLines)
Product product = new Product();
String[] tokens = line.split("-");
product.setId(tokens[0]);
product.setDepartment(tokens[1]);
product.setName(tokens[2]);
product.setPrice(tokens[3]);
product.setStock(tokens[4]);
System.out.println(product.toString())
}
} catch (IOException e) {
e.printStackTrace();
}
}
For future readers.
I had double quotes surrounding my csv (comma separated values) file.
And had some doubles and ints.
I also has going nuts trying to find a "bad line" and the value that was barfing.... in the csv file. Thus my exception with a decent message.
My "delimiter" is a comma and carriage return. And I deal with the double quotes "at the column level".
Here is what I came up with.
/* I know, a java example with the imports listed out ! shocking !! */
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
private void loadFromFile() {
Collection<MyCustomObject> items = new ArrayList<MyCustomObject>();
int lineNumber = 0;
String nextValue = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("MyFile.txt").getFile());
Scanner input = new Scanner(file)
.useDelimiter(",|\\R")
.useLocale(Locale.ENGLISH);
;
/* skip the header */
input.nextLine();
while (input.hasNext()) {
lineNumber++;
nextValue = input.next().replace("\"", "");
String zipCodeValue =nextValue;
nextValue = input.next().replace("\"", "");
String city = nextValue;
nextValue = input.next().replace("\"", "");
String usaState = nextValue;
nextValue = input.next().replace("\"", "");
double latitude = Double.valueOf(nextValue);
nextValue = input.next().replace("\"", "");
double longitude = Double.valueOf(nextValue);
nextValue = input.next().replace("\"", "");
int population = Integer.valueOf(nextValue);
items.add(new MyCustomObject(zipCodeValue, city, usaState, latitude, longitude, population));
}
} catch (Exception ex) {
throw new RuntimeException(String.format("Line number '%s, nextValue '%s''", lineNumber, nextValue), ex);
}
}
Sample text (csv) file:
"ZIPCODE","CITY","STATE","LATITUDE","LONGITUDE","POPULATION"
"06778","NORTHFIELD","CT",41.707,-73.105,555
"06779","OAKVILLE","CT",41.595,-73.081,777
"06782","PLYMOUTH","CT",41.657,-73.041,888

Java error message at main method

I am new in this Java journey, at College they are asking me to
"Define five String variables in the main method called: shipmentNum, supplierName, revDate, revTime, employeeNum." And assign the following text:99, Costco, 12/15/2011, 10:25 AM, 33."
I have this so far, but is giving an error message: "the local variable shipmentNum is never read", I don't see why am I getting this error message.
package c1;
public class ShipmentApp {
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println("99");
System.out.println("Costco");
System.out.println("12/15/2011");
System.out.println("10:25 AM");
System.out.println("33");
}
}
What you are seeing is a compiler warning, not an error. This is basically Java trying to help you find flaws in your code by analyzing what you wrote and detecting common mistakes.
In this case, Java recognized that you assigned values to a bunch of variables, but after that never use those variables again.
You probably want to write out the values of the variables, not the assigned values again.
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum );
System.out.println(supplierName );
System.out.println(revDate );
System.out.println(revTime );
System.out.println(employeeNum );
}
Thats warning not error but try this.
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);
}
or just try:
package c1;
public class ShipmentApp{
public static void main(String[] args){
System.out.println("99");
System.out.println("Costco");
System.out.println("12/15/2011");
System.out.println("10:25 AM");
System.out.println("33");
}
}
What you are receiving are warnings because you are not actually ever reading any of the variables you have declared. You could correct this by passing the variables to println instead of typing out the strings twice.
Being that these are only warnings, they should not affect the ability of the program to compile and/or execute. While you could conceivably ignore such warnings, it's usually wise to at least analyze what they are being caused by.
It's a warning that the java compiler tells you that you defined a variable but never used it.
The purpose of a variable, is that it stores information that will be used at some later point in your code. Java gives you a warning, because if you define a variable but never use it you've likely made a mistake. This is because variables that are never used are basically nonsense, and should never have been declared.
Try these print statements:
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);
That's is not an Error,It is just a warning shown by the IDE or compiler. There is no issue in this code to compile and run.
You may want to do as follows
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);
You are writing the text out, not the value of the variables. It isn't an error, just a warning. You should probably change your code to this:
package c1;
public class ShipmentApp{
public static void main(String[] args){
String shipmentNum = "99";
String supplierName = "Costco";
String revDate = "12/15/2011";
String revTime = "10:25 AM";
String employeeNum = "33";
System.out.println(shipmentNum);
System.out.println(supplierName);
System.out.println(revDate);
System.out.println(revTime);
System.out.println(employeeNum);
}
}
this message is just to notice you, you have some variables haven't been used. It is not a error. if you dont want to see this warning or you cannot stand it, you can add #supresswarnings annotation at the beginning of the class. or you just follow others' suggestion to use the variables you have created.

Categories