Converting String to appropriate Java object - java

I have a String in this format (including curly brackets):
{id=123, vehicle_name=Tesla Model X, price=80000.00, ... }
What is the appropriate Java object to represent this String, and how can I convert it to that object?
I would like to be able to query the object to retrieve its values easily, eg. obj.get("vehicle_name"). I've tried converting it to JSON using JSONObject however this expects colons as the delimiters between keys and values, rather than the equals sign.

String itself is a java object.
Parsing String and filling up a java object is not clean.
You can create a java pojo Vehicle with attributeS like id,
vehicle_name etc. Assuming your String will always follow a same
pattern.
Parse the String, and fill this Vehicle pojo.
Below is just a simple example, on how to do it :-
public class Test {
public static void main(String[] args){
String text="{id=123, vehicle_name=Tesla Model X, price=80000.00}";
text=text.replaceAll("[{}]", "");
String[] commaDelimitArray=text.split(",");
Vehicle vehicle=new Vehicle();
for(int i=0;i<commaDelimitArray.length;i++){
String[] keyValuePair=commaDelimitArray[i].split("=");
String key=keyValuePair[0].trim();
String value=keyValuePair[1].trim();
if("id".equals(key)){
vehicle.setId(value);
}
else if("vehicle_name".equals(key)){
vehicle.setVehicleName(value);
}
else if("price".equals(key)){
vehicle.setPrice(value);
}
}
System.out.println(vehicle.getId()+" |"+vehicle.getVehicleName());
}
static class Vehicle{
private String id;
private String vehicleName;
private String price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
}

This appears to be an assignment in creating Object classes. If so, you want to create something like this:
public class Car {
int id;
String name;
double price;
//include any other necessary variables
public Car(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
//include any other variables in constructor header and body
}
public void setID(int newID) {
id = newID;
}
public int getID() {
return id;
}
//add getters and setters for other variables in this same manner
}
Note that you could alternatively create a constructor that takes no parameters and initializes variables to default values, then set the values individually using the setter methods.
In your main class, what you want to do is extract the appropriate substrings from your String to pass to the constructor (or setters). There are various ways of doing this (you can read about some ways here); I would personally recommend using regular expressions and a Matcher.

If I had such a string which needed to be converted to an object I would create a class with a static method which returns a Vehicle object. Then you can do whatever you want with that object. A few getters and setters and you should be good to go.
I have come up with some code which should work as you expect if I have understood your question :)
There is quite a few comments so this should help you understand the code logic.
The Vehicle Class is where all parsing happens in the static method named createVehicle(String keyValueString).
The main class:
import java.util.ArrayList;
import java.util.List;
public class main {
public static void main(String[] args) {
String vehicleString = "{id=123, vehicle_name=Tesla Model X, price=80000.00}";
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Vehicle vehicle;
// call the static method passing the string for one vehicle
vehicle = Vehicle.createVehicle(vehicleString);
// if the id is -1, then the default constructor fired since
// there was an error when parsing the code.
if(vehicle.getId() == -1 ) {
System.out.println("Check your data buddy.");
} else {
vehicles.add(vehicle);
}
for(Vehicle v : vehicles){
System.out.println("Vehicle id: " + v.getId());
System.out.println("Vehicle name: " + v.getVehicle_name());
System.out.println("Vehicle price: " + v.getPrice());
System.out.println();
}
}
}
The Vehicle Class:
import java.math.BigDecimal;
public class Vehicle {
// declare your attributes mapped to your string
private int id;
private String vehicle_name;
private BigDecimal price;
// Start Constructor
// Default Constructor
public Vehicle() {
this.setId(-1);
this.setVehicle_name("Empty");
this.setPrice(new BigDecimal(0.00));
}
public Vehicle(int id, String vehicle_name, BigDecimal price) {
this.setId(id);
this.setVehicle_name(vehicle_name);
this.setPrice(price);
}
// End Constructor
// Start Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVehicle_name() {
return vehicle_name;
}
public void setVehicle_name(String vehicle_name) {
this.vehicle_name = vehicle_name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
// End Getters and Setters.
// Start Methods and Functions
// Given a string returns a string array split by a "," and with
// "{}" removed.
private static String[] splitString(String keyValueString) {
String[] split;
// Clean string from unwanted values
keyValueString = keyValueString.replaceAll("[{}]", "");
split = keyValueString.split(",");
return split;
}
// Add a vehicle given a formatted string with key value pairs
public static Vehicle createVehicle(String keyValueString) {
int id = 0;
String vehicle_name = "";
BigDecimal price = null;
String[] split;
Vehicle vehicle;
split = splitString(keyValueString);
// Loop through each keyValue array
for(String keyValueJoined : split){
// split the keyValue again using the "="
String[] keyValue = keyValueJoined.split("=");
// remove white space and add to a String variable
String key = keyValue[0].trim();
String value = keyValue[1].trim();
// check which attribute you currently have and add
// to the appropriate variable
switch(key){
case "id":
id = Integer.parseInt(value);
break;
case "vehicle_name":
vehicle_name = value;
break;
case "price":
try {
price = new BigDecimal(Double.parseDouble(value));
} catch (NumberFormatException e) {
e.printStackTrace();
}
break;
default:
System.out.println("Attribute not available");
return null;
}
}
// if any of the values have not been changed then either the
// data is incomplete or inconsistent so return the default constructor.
// Can be removed or changed if you expected incomplete data. It all
// depends how you would like to handle this.
if(id == 0 || vehicle_name.equals("") || price == null){
vehicle = new Vehicle();
} else {
//System.out.println(id);
vehicle = new Vehicle(id, vehicle_name, price);
}
return vehicle;
}
// End Methods and Functions
}
The program, given the string provided, returns the following when accessing the newly created object attributes using the getters:
Vehicle id: 123 Vehicle name: Tesla Model X Vehicle
price: 80000
Hope this helps.

Related

JAVA Store Program isn't outputting the correct numbers

I was creating a Java program for my OOP class. The program is supposed to be the start of a store interface and we are going to build off it during the rest of the semester. Whenever I was to add a new product and try to access how much of it is in stock my program says the "Id DNE -1" which is only supposed to print when an id is called and it doesn't exist. I'm not too sure why it's not recognizing the product I just put in. Below are all my classes that are used. I think the error has to be somewhere in my inventory class but I'm not too sure. Any tips or tricks for OOP would greatly be appreciated as well. Cheers
public class main
{
public static void main(String[] args)
{
StoreManager r3 = new StoreManager();
Inventory r4 = new Inventory();
r4.addNewProduct(1,"apple",1.50,50);
System.out.println(r3.qCheck(1));
}
}
public class StoreManager
{
private Inventory store1 = new Inventory();
private Product store2 = new Product();
static Inventory r4 = new Inventory();
public StoreManager(){}
public int qCheck(int id)
{
if (store1.getStock(id) < 0)
{
System.out.println("Id DNE");
return -1;
} else
{
return store1.getStock(id);
}
}
public double dqcheck(int id, int desiredQuantity) {
if (store1.getStock(id) >= desiredQuantity) {
store1.removeStock(id, desiredQuantity);
double cost = store2.getPrice() * desiredQuantity;
return cost;
}
else {
System.out.println("id DNE");
}
return -1;
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Inventory
{
//Var Declarations
private int quantity;
// FIXME: 2021-02-07 idk if im usin type right
private Product type;
//Hashmap for the data structure in this class using the Product is gonna be a key
// the value is the Integer for the quantity
private Map<Product,Integer> invt = new HashMap<>();
//blank constructor
public Inventory()
{
}
// FIXME: 2021-02-05 Getter and setter methods not really in use
public int getQuantity(){return quantity;}
public Product getType(){return type;}
/*
Used to initialize a new product and its stock into our Hashmap
the Quantity is the Value of our hashmap while we are using the
Product as a whole to be the key
no return type
*/
public void addNewProduct(int id,String name, double price, int quantity)
{
Product product = new Product(name, id, price);
invt.put(product,quantity);
}
/*
Used to get the get for a given id
compares the Id to one of the ids in the Key values to find the product
returns an int for the amount in stock or a -1 as an error if the id doesn't exist
*/
public int getStock(int id)
{
Set<Product> set = invt.keySet(); // Conversion of keys into sets
Iterator<Product> it = set.iterator(); // the only way i could get the code to interate throughout the keys
while (it.hasNext())//Only way i could go through the code
{
type = it.next();// FIXME: 2021-02-07 Idk if type is being used right here but i needed a buffer variable for it to work
Product a = it.next();
if (a.getId() == id)
{
return invt.get(type);//type is an object of Product here so we can use it as a key
}
}
return -1;//representation of error ID Dne
}
/*
Used to add a given Stock for a given Id
void doesnt return anything
assuming inpputed id exists if Dne doesnt do anythin or return an error
*/
public void addStock(int id, int amountToAdd)
{
//Possibly make this hashmap id check into another private method and call
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id)
{
invt.put(type, invt.get(type)+amountToAdd);
return;//exit the function after the addtion is done
}
}
}
/*
Used to remove a given amount of product from stock in reference to a given Id
void doesnt return anythin
assuming id exits otherwise it does nothin
*/
public void removeStock(int id, int amountToRemove)
{
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id && invt.get(type) - amountToRemove >= 0)//checks if the id exits and if there whould be enough stock to remove
{
invt.put(type, invt.get(type)-amountToRemove);
return;
}
}
}
/*
Prints all product information in reference to the id
*/
public void getInfo(int id)
{
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id)
{
System.out.println("Name: "+type.getName());
System.out.println("Id: "+type.getId());
System.out.println("Price: "+type.getPrice());
System.out.println("Quantity: "+ invt.get(type)); // FIXME: 2021-02-07 Idk if Quanitity and Id are needed here
}
}
}
}
public class Product
{
private String name;
private int Id;
private double price;
public Product(String Name, int Id,double Price)
{
this.name = Name;
this.Id = Id;
this.price = Price;
}
public Product()
{
}
//Getter Methods
public String getName() {return name;}
public int getId() {return Id;}
public double getPrice() {return price;}
}
public class main
{
public static void main(String[] args)
{
StoreManager r3 = new StoreManager();
r3.store1.addNewProduct(1,"apple",1.50,50);
System.out.println(r3.qCheck(1));
}
}
Use the Inventory object that belongs to StoreManager, that's the only one it can access.

JAVA adding object to ArrayList of different Class,constantly replace 0 index and doesnt get bigger

I am trying to finish my home assignment for programming class, unfortunately getting stuck through half of it ,due to my stupidity. ArrayList that I have created overwrites 0 index constantly.
Here are my classes for creating invoices:
import java.util.ArrayList;
public class Order
{
private String customerName;
private ArrayList<LineItem> items = new ArrayList<LineItem>();
public Order(String customerName)
{
this.customerName = customerName;
}
public String getCustomerName()
{
return customerName;
}
public ArrayList<LineItem> getItems()
{
return this.items;
}
public double getOrderTotal()
{
double totalOrder = items.get(0).getTotalPrice();
return totalOrder;
}
public void addItem(String description,double unitPrice, int quantity)
{
LineItem object = new LineItem(description,unitPrice,quantity);
items.add(object);
}
public String toString()
{
String.format("%n%-20s%-15s%-15f%-15f",items.get(0).getDescription(),
items.get(0).getQuantity(),items.get(0).getUnitPrice(),getOrderTotal());
return p;`
}
}
public class LineItem
{
private String description;
private double unitPrice;
private int quantity;
public LineItem(String description,double unitPrice, int quantity)
{
this.description = description;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public String getDescription()
{
return this.description;
}
public double getUnitPrice()
{
return this.unitPrice;
}
public int getQuantity()
{
return this.quantity;
}
public double getTotalPrice()
{
return this.unitPrice * this.quantity;
}
public String toString()
{
return String(this.description,this.unitPrice,this.quantity)
}
}
AND a part of ... while LOOP for main class
do
{
customerName = AssignmentHelper.getRequiredStringInput("Please enterthe customer's name: ","A customer name must be entered!");
newOrder = new Order(customerName);
newOrder.addItem(description,unitPrice,quantity);
} while(Character.toString(userAnswer).equalsIgnoreCase ("Y"));
Your loop creates a new Order object in each iteration :
newOrder = new Order(customerName);
Each Order object has a new empty ArrayList, which is why it seems the first index is always overwritten.
If you want a single ArrayList to hold all the items, you should create a single Order object prior to the do-while loop.
newOrder = new Order(customerName);
do {
...
newOrder.addItem(description,unitPrice,quantity);
} while(Character.toString(userAnswer).equalsIgnoreCase ("Y"));
In the loop, a new order object is created which has two fields (customer name and an Arraylist of line items). Initially the ArrayList will be empty.The call to addItem object creates a new Lineitem object and add its to the ArrayList items. Therefore the lineItem object will always be added to index zero.
Create a new object only when a new customer is added.You can have a HashMap where key is the customer name. If the key already exists add to the same object else create a new order object and it to the Map.

How can I make enumeration class with number shaped String

First, thank you for your help!!
What I want to make with an Enumeration class is a Menu of a restaurant. The menu components have its own id which is number, and name.
001("Pasta"),
002("Pizza"),
003("Nuddle"),
004("Steak"),
005("Rice")
Above code my first idea but, I got errors, so I thought only String value can be the components of Enumeration. So, I changed the code like below but it generated error again.
"001"("Pasta"),
"002"("Pizza"),
"003"("Nuddle"),
"004"("Steak"),
"005"("Rice")
The numbers are just IDs of food, so it can have String type. How can I make it?
Enums names cannot start with numbers. If you want to use Enums, I would suggest to use something like this:
public enum Food {
PASTA("Pasta", 1),
PIZZA("Pizza", 2);
/** state variables */
private String name;
private int id;
/** Constructor */
Food(String name, int id) {
this.name=name;
this.id=id;
}
/** Accessors */
public String getName() {
return name;
}
public int getId() {
return id;
}
}
you can use in this way. Or how about add some character like...F001, F002
public class Tester {
static enum Food {
PASTA("001"), PIZZA("002"), NOODLE("003");
private String number;
Food(String number){
this.number = number;
}
public String getNumber(){
return this.number;
}
}
public static void main(String[] args) {
System.out.println( Food.PIZZA.getNumber());
}
}
You can do something like this. First create a static map and put number and string value as a key value pair and write a utility to retrieve a food value based on the given number key value after creating your constructor to populate both fields.
public enum MenuEnum {
ONE(1, "Pasta"), TWO(2, "Pizza"), THREE(3, "Noodle");
private int number;
private String name;
private MenuEnum(int number, String name) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public String getFoodByNumber(int key) {
return foodMap.get(key) != null ? foodMap.get(key) : null;
}
private static final Map<Integer, String> foodMap = new HashMap<Integer, String>();
static {
for (MenuEnum val : MenuEnum.values()) {
foodMap.put(val.getNumber(), val.getName());
}
}

How to check if an array in an arraylist contains a certain value?

I have an array list which contains arrays of type String. I create the array list and add arrays to it with the following code:
List<String[]> transaction = new ArrayList<String[]>();
String[] transactionLine = new String[7];
transactionLine[0] = "0";
transactionLine[1] = "1";
//.....
transactionLine[6] = "some value";
transactionLines.add(transactionLine);
Now I want to test if one of the arrays contain a certain value. I tried it like this, but then it checks for an array and not an element of an array:
if(transactionLines.contains("some value")) {
//Do some stuff with it
}
I know this doesn't work, but I don't now how to do it otherwise. I couldn't find any post of this already on Stackoverflow (not with the logical search terms for this problem anyway).
Note: I have chosen this structure of arrays in an arraylist, because I have a fixed number of columns (as suggested in how to create dynamic two dimensional array in java?).
Any help is greatly appreciated!
#assylias suggestion to use the object oriented way is good, but his example does not tell if the list contains a transaction where one property has a certain value. This example does:
public class Test {
public static void main(final String[] args) {
final List<TransactionLine> transaction = new ArrayList<>();
transaction.add(new TransactionLine(1, "some value"));
transaction.add(new TransactionLine(2, "another value"));
transaction.add(new TransactionLine(3, "yet another value"));
System.out.println(containsName(transaction, "some value"));
System.out.println(containsName(transaction, "non-existent value"));
}
// Iterates over all transactions until a transaction is found that has the
// same name as specified in search
private static boolean containsName(final List<TransactionLine> transaction, final String search) {
for (final TransactionLine transactionLine : transaction) {
if (transactionLine.getName().equals(search)) {
return true;
}
}
return false;
}
private static class TransactionLine {
private int id;
private String name;
public TransactionLine(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
}
Here is an example with two classes (Transaction and TransactionLine):
Test:
public class Test {
public static void main(final String[] args) throws Exception {
final Transaction transaction = new Transaction();
transaction.add("some name");
transaction.add("another name");
transaction.add("yet another name");
System.out.println(transaction.containsName("some name"));
System.out.println(transaction.containsName("non-existent name"));
}
}
Transaction:
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private final List<TransactionLine> transactionLines = new ArrayList<>();
public void add(final String name) {
final TransactionLine tl = new TransactionLine(transactionLines.size(), name);
transactionLines.add(tl);
}
public boolean containsName(final String name) {
for (final TransactionLine transactionLine : transactionLines) {
if (transactionLine.getName().equals(name)) {
return true;
}
}
return false;
}
}
TransactionLine:
public class TransactionLine {
private int id;
private String name;
public TransactionLine() {
}
public TransactionLine(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
The object oriented way of solving your problem would be to create a class:
class Transaction {
private final int id;
private final String name;
//etc.
}
Then if you need to test if a given transaction is in the list you could implement equals and hashcode in that class, which would enable you to call:
if(transactionLines.contains(someTransaction)) { ... }
If you just need to find transactions with a specific characteristics, you would need to iterate over the list and check each transaction, for example:
Transaction result = null;
for (Transaction t : transacionLines) {
if(t.getName().equals("some value") {
result = t;
break;
}
}
public static boolean isListOfStringArraysContainsString(List<String[]> arrayList, String s) {
for (String[] arr : arrayList) {
for (String string : arr) {
if ((string != null) && (string.equals(s))) {
return true;
}
}
}
return false;
}
Provided code do exactly what you are asking about, but solution provided by #assylias is proper
I got your point. By using ArrayList you are trying to make an array of another array of strings. But you have made one simple mistake.This is how you tried to retrieved a String inside an array inside an ArrayList:
if(transactionLines.contains("some value")) {
//Do some stuff with it
}
This "some value" is a string present in String array "transactionLine" and not referred by the List "transactionLines" (which is referring to ArrayList object).
Instead this is what you should have done:
List<String[]> transactionLines = new ArrayList<String[]>();
String[] transactionLine = new String[7];
transactionLine[0] = "0";
transactionLine[1] = "1";
transactionLine[2] = "something";
transactionLine[3] = "3";
transactionLine[4] = "4";
transactionLines.add(transactionLine);
String[] mySL=transactionLines.get(0);
System.out.println(mySL[2]);
if (mySL[2].equals("something")) {
//some code
} else {
//some code
}
Hope this helps.

How to assign value to this function in java incompatible types

How to assign value to this function in Java incompatible types?
public class CustomerInfo implements Serializable {
private static final long serialVersionUID = 9083257536541L;
protected String id;
protected String searchkey;
protected String taxid;
protected String name;
protected String postal;
/** Creates a new instance of UserInfoBasic */
public CustomerInfo(String id) {
this.id = id;
this.searchkey = null;
this.taxid = null;
this.name = null;
this.postal = null;
}
public String getId() {
return id;
}
public String getTaxid() {
return taxid;
}
public void setTaxid(String taxid) {
this.taxid = taxid;
}
public String getSearchkey() {
return searchkey;
}
public void setSearchkey(String searchkey) {
this.searchkey = searchkey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPostal() {
return postal;
}
public void setPostal(String postal) {
this.postal = postal;
}
public String printTaxid() {
return StringUtils.encodeXML(taxid);
}
public String printName() {
return StringUtils.encodeXML(name);
}
#Override
public String toString() {
return getName();
}
}
private CustomerInfo selectedCustomer;
public CustomerInfo getSelectedCustomer() {
// construct a CustomerInfo from the data in your String
return selectedCustomer;
}
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
selectedCustomer = (CustomerInfo) jListCustomers.getSelectedValue();
//test code
String testing = m_jtxtName.getText();
System.out.println("Now the selectedCustomer is dispayed!");
System.out.println(selectedCustomer);
System.out.println(testing);
//test code
dispose();
}
In the above shown code, I need the string testing value to be assigned to selectedCustomer. How can I assign the value? This is the error I get:
selectedCustomer = m_jtxtName.getText();
incompatible types
required: CustomerInfo
found: String
You can't!!!
selectedCustomer is an object of type CustomerInfo.
m_jtxtName.getText() returns a String
You can't assign a String to a CustomerInfo.
Probably you need to do something like:
int id = 1; //Or whatever new id you have.
String name = m_jtxtName.getText();
selectedCustomer = new CustomerInfo(name); //or whatever id you have.
selectedCustomer.setName(name); //or whatever name you have.
EDIT:
Something is missing from your class. Either it needs setter methods (it has only getters now, so you can't set other properties as name etc) or it needs a constructor with four arguments like:
public CustomerInfo(String id, String searchKey, String taxid, String name, String postal) {
this.id = id;
this.searchKey = searchKey;
// etc
In this case, you might have six jtextfields in your screen, so te user can fill all fields and the create the Customerinfo object by passing all parameters to the constructor.
you cannot do it by simply casting a String to a CustomerInfo object, but you could extend your CustomerInfo but you could try something like this:
public class CustomerInfo {
[...]
public static CustomerInfo createCustomerInfo(String data) {
// construct a CustomerInfo from the data in your String
return createdCustomerInfo;
}
}
I don't know what data you have in that String so i can not give you an advice how to implement this. e.g. If it is the ID you could use this to retrieve the CustomerInfo from database or something like that.

Categories

Resources