I have a problem in retriving data with two decimal places from the database.
I was using resultset.getDouble() method. But this gives me only 1 decimal places on the result. I tried using the DecimalFormat to convert to 2 decimal. When I run my code, I'm getting the error "String cannot convert to double" from DisplayFood.java
DisplayFood.java
Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
DecimalFormat df = new DecimalFormat("#.00");
String query = "SELECT * FROM food";
statement = connection.createStatement();
resultset = statement.executeQuery(query);
while(resultset.next())
{
FoodRecord foodmenu = new FoodRecord();
foodmenu.setItemName(resultset.getString("itemName"));
foodmenu.setPrice(df.format(resultset.getDouble("price")));
foodmenu.setRestaurant(resultset.getString("restaurant"));
food.add(foodmenu);
}
FoodRecord.java
public class FoodRecord {
private String itemName;
private double price;
private String restaurant;
public FoodRecord() {
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
}
You get this Error bacause You are trying to set a String value in a double Field.
Use resultset.getDouble("price") to read the items Price from resultset.
To print the Price with two decimal Places you can use your formatter with System.out.println like df.format(foodMenu.getPrice()).
I was using resultset.getDouble() method. But this gives me only 1
decimal places on the result
The getDouble() method returns the value number as a double is represented in java.
The getDouble() javadoc :
Retrieves the value of the designated column in the current row of
this ResultSet object as a double in the Java programming language.
It means if your number value is 10.5, the double will have as value 10.5 and not 10.50.
I tried using the DecimalFormat to convert to 2 decimal
DecimalFormat.format(double number) formats a double as a String with a specific format.
The format specified is here in your code :
DecimalFormat df = new DecimalFormat("#.00");
So, yes you cannot assign a Double to a String as these are not compatible types.
To solve your problem, you have to store the result of DecimalFormat.format(double number) in a String.
But it is indeed not not consistent with the FoodRecord class where price is a double field : private double price;
Changing price from double to String in the class is not necessarily the best way for two reasons :
the visual representation of a data should not change the data value.
If the decimal is on 4 floating value (for example : 10.5445), formatting it to 10.54 and storing the information in the class only as a String field truncates the data value. If you store again the value in your database, it changes the initial value while the object was not modified by the client.
you could not any longer have a simple setPrice() method with a double (so in a natural way) as you should perform some computations in the setPrice() method to change the double to a String.
To solve your problem, you could introduce a new method that returns the formatted price :
public String getFormatedPrice(){
return df.format(resultset.getDouble("price"));
}
If getFormatedPrice() is frequently invoked, the result could be cached instead of invoking df.format().
Related
Assuming there is a Class called Product which has two product object called p1 and p2 which have the following fields:
P1--> int productId =123, String name ="iPhoneS8", int unitPrice
=1000, String datMfs ="12/18/2017". P2--> int productId =124, String name ="Samsung Galaxy S8", int unitPrice =1200, String datMfs
="05/22/2016".
The first question is
1), Write a java code for the product including getters and setters
methods, any three overloaded constructors including default. My
solution code is the following.
class Product {
Product() {//default Constractor
}
Product(int price) {//Overloaded Constractor1
}
Product(String name) {//Overloaded Constractor2
}
Product(String name, double pri) {//Overloaded Constractor3
}
Product(int name, double pri) {//Overloaded Constractor4
}
// The following is the product fields
private int productId;
private String name;
private int unitPrice;
private String dateMdft;
//The following is getters and setters
public int getproductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getproductName() {
return name;
}
public void setProductname(String name) {
this.name = name;
}
public int getproductunitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
public int getUnitPrice() {
return unitPrice;
}
public void setDateMan(String dateMdft) {
this.dateMdft = dateMdft;
}
public String getDateManftd(String dateMdft) {
return dateMdft;
}
The second Question is
2), Write a method called printOutedDatedProduct(from the above) and
iterate through the object and print out the data for only the
outdated product to the screen in CSV format. the method should print
124, Samsung Galaxy S8,1200, 5/22/2016.
I am really Struggling to write the method and print out the outdated product so I really appreciate the community if anybody helps me and I am also really open to take any comments as far as the solution to the first question is concerned too. Great Thanks!
I would recommend to store date in LocalDate object. Why LocalDate? It is a well-written and tested class for date mainetenance.
How to instantiate and compare:
LocalDate d1 = LocalDate.of(2000, 06, 26);//YYYY-MM-DD
LocalDate d2 = LocalDate.now();
System.out.println(d1.compareTo(d2));//if d1 < d2, returns negative integer (difference between dates), otherwise positive integer.
What does d1.compareTo(d2)? It returns an integer representing the difference bwtween dates. It takes the first terms of dates that don't match and subtracts the second from the first. For example: 2019-03-14 compared to now (2019-03-29) will return 14-29 = -15.
You need to call compareTo(LocalDate) method for each LocalDate field of Product instance and compare with LocalDate.now();. When the numer is negative, print info about the product.
Java by default calls the toString method when you try to use an object as a String then what you need to do is to prepare the Product toString method first like this below:
public String toString(){
return productId+", "+name+", "+unitPrice+", "+dateMdft;
}
after that, the printing is going to be easy but you need to check for the date, manipulating a date as a String will cost you a lot. you can find java dates best practices presented in a good way here
after you learned how to use the Date class and how to check your date now you all you need to write the function that loops on the array you have and checks the date and print your data.
First, think about right datatypes for fields. You can use String for date filed, but how will you compare this dates? There is powerful JDK datetime API, let's use it. I'll recommend LocaDate, as you need only date part.
Second. Your constructors shouldn't be empty or useless. You could initialize object fields in constructors. For example:
Product(String name) {
this(name, 0);
}
Product(String name, int unitPrice) {
this(name, unitPrice, LocalDate.now());
}
Product(String name, int unitPrice, LocalDate dateMdft) {
this.name = name;
this.unitPrice = unitPrice;
this.dateMdft = dateMdft;
}
The next step is method for string representation of object. You could override toString or create another.
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/YYYY");
#Override
public String toString() {
return productId + "," + name + "," + unitPrice + "," + dateTimeFormatter.format(dateMdft);
}
And the last, filter and print.
public static void main(String args[]) {
List<Product> products = new ArrayList<>();
products.add(new Product("1", 100, LocalDate.now().minusDays(1)));
products.add(new Product("2", 150, LocalDate.now().minusDays(2)));
products.add(new Product("3", 250, LocalDate.now()));
System.out.println("Via for loop:");
for (Product p: products) {
if (p.getDateMdft().isBefore(LocalDate.now())) {
System.out.println(p);
}
}
System.out.println("Via stream API:");
products
.stream()
.filter(p -> p.getDateMdft().isBefore(LocalDate.now()))
.forEach(System.out::println);
}
Perhaps I am overreaching on the use of JAVA annotations, but can someone explain to me whether what I am trying to achieve is possible. If it is, please point me in the right direction.
I have a simple emum containing currencies that are to be used in my application.
public enum Currency{
EURO, DOLLARS
}
I want to persist an amount BigDecimal together with its associated currency. I want to be able to retrieve both whenever needed. I know I can change the amount to string and concatenate them but isn't there a smarter way to do it, perhaps using annotations?
You could just create an object named Money like so:
public class Money{
private Currency currency;
private BigDecimal amount;
public Money(Currency currency, BigDecimal amount){
this.currency = currency;
this.amount = amount;
}
public Currency getCurrencyType(){
return currency;
}
public BigDecimal getAmount(){
return amount;
}
}
Then to create an object from this class, you would just write something like this:
Money money = new Money(Currency.EURO, new BigDecimal("24322.21"));
And then you can retrieve the values for by calling the get functions:
System.out.println(money.getAmount().toString() + " " + money.getCurrencyType());
I know the question seems weird, but I'll try to explain it the best that I can. I am doing an Amusement Park Project where you have methods for the tickets, merchandise, etc. I made a Ticket class with the methods, but now I'm in the AmusementPark class trying to create a method of taking the date from that class and putting it into a new ArrayList. Maybe my code will help explain it.
First, here is my Ticket class......
import java.text.DecimalFormat;
public class Ticket {
private long number;
private String category;
private String holder;
private String date;
private double price;
private boolean purchased;
Ticket(long num, String cat, String h, String dt, double pr, boolean pch){
this.number= num;
this.category= cat;
this.holder= h;
this.date= dt;
this.price= pr;
this.purchased= pch;
}
long getNumber(){
return number;
}
String getCategory(){
return category;
}
String getHolder(){
return holder;
}
String getDate(){
return date;
}
boolean getPurchased(){
return purchased;
}
double getPrice(){
return price;
}
void setPrice(double pr){
price= pr;
}
void setChangePurchased(boolean newStatus){
purchased= newStatus;
}
#Override
public String toString(){
DecimalFormat dm= new DecimalFormat("#.##");
String disp;
disp = "Number: " + getNumber() + "\nCategory: " + getCategory() + "\nTicket Holder Name: " + getHolder() + "\nDate: " + getDate()
+ "\nPrice: " + dm.format(getPrice()) + "\nPuchased Completed?: " + purchased;
return disp;
}
}
Here is some of the Pseudo Code explaining what I am trying to do with the next class I'm about to post.
Create an ArrayList from the Ticket class.
//The ticket class has the following constructors....
// (Ticket number of type long, category of type String, Ticket holder of type String, Date of admission, purchase price of type double, variable named "purchased" whether the ticket has been paid for of type boolean)
//One of the variables of type class is tickets in which the ticket class is made into an ArrayList.
//The next task is to get tickets for dates where they are available, which is done by searching tickets where the purchase is not completed.
Create a public ArrayList<Date> method called getTicketDates(){
Create a variable called theDateArray which is a new ArrayList<Date>;
For(starting at the first position of the list, go through the the entire list incrementing by one){
if (boolean purchased of the Ticket ArrayList is false)**{
Add the date of the object from the Ticket ArrayList to theDateArray ArrayList.}** //This stores the dates of all tickets not yet purchased into the new ArrayList.
}
Return theDateArray;
}
//The next task is to search through theDateArray for only select dates and post the available tickets for that date as an integer.
Create a method which displays the number of tickets for a specified date by going through theDateArray (Date date) {
For(starting at the first position of theDateArray, go through the entire list and look for tickets that have a particular date){
if (the date== entered date){
Include the ticket as one of the tickets available for that date.
}
}
Return the total number of tickets available for that date as a type integer.
}
Okay, now here is my AmusementPark class. Note It is not finished. I'm just trying to get this one part done....
import java.util.ArrayList;
import java.util.Date;
public class AmusementPark {
private ArrayList<Ticket> tickets;
private ArrayList<Merchandise> merchandise;
private String name;
AmusementPark(String name){
this.name=name;
this.tickets = new ArrayList<Ticket>();
this.merchandise= new ArrayList<Merchandise>();
}
String getName(){
return name;
}
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
String date = Ticket.getDate(); //This is not working. See Reason Below.
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(date);
}
}return theDateArray;
}
}
Okay, so now what happens when I try to call the method of getDate() from the Ticket class, it's not allowing me to use it for the reason that I cannot make a static reference to a non-static method. However, when I try to make the method static, it messes up the other class by saying I cannot make a static reference to a non-static field.
An ArrayList of the Ticket class has already been made. I need it to scroll through that list, get the ones where the boolean is false, and add the date to the next ArrayList.
Does this at all make sense?
Any ideas that would be better?
Let's take your method.
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
String date = Ticket.getDate(); //This is not working. See Reason Below.
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(date);
}
}
return theDateArray;
}
Notice the problem on the Ticket.getDate() that you try to do whithout an instance, so a static call. But what you explain, you want the date for the Ticket of the list tickets. Good, you are iterating it after but are pushing this strange value date coming from a "static method".
You problem is that the instance holding the date you want is in the list. You are using it to see if it is purchased or not. So call the method on those instance to get the value :
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
But better :
Ticket ticket;
for (i=0; i<tickets.size(); i++){
ticket = tickets.get(i);
if(ticket.getPurchased()== false){
theDateArray.add(ticket.getDate());
}
}
If I understand it correctly what is required here is to extract dates for not purchased tickets into separate dates array. And you already got it correctly in your pseudocode, you just need to follow it more strictly during implementation:
public ArrayList<String> getTicketDates() {
ArrayList<String> theDateArray = new ArrayList<>();
// iterate over all tickets
for ( Ticket ticket : tickets ) {
// if ticket not purchased
if ( ! ticket.getPurchased() ) {
// add ticket's date into array
theDateArray.add( ticket.getDate() );
}
}
return theDateArray;
}
DON'T MAKE STATIC REFERENCE !Instead of writing a what's code answer let's focus on the workaround of problem.
Whenver you will set values to instance variables of TICKET Class it will refer to a particular object (new ticket()) to access its values if you make variables of class staticValues will be stored when class is loaded and not when object is created but arraylist items need to have
Object of ticket Class.
A simple approach should be
ASSIGN THE VALUES TO VARIABLES WHEN EVER YOU MAKE AN OBJECT OF TICKET CLASS BY BY PASSING VALUES IN ITS CONSTRUCTOR AND THEN
ADD THOSE OBJECTS TO ARRAYLISTITEMS
ticket class
public class Ticket {
private long number;
private String category;
private String holder;
private String date;
private double price;
private boolean purchased;
Ticket(long num, String cat, String h, String dt, double pr, boolean pch){
this.number= num;
this.category= cat;
this.holder= h;
this.date= dt;
this.price= pr;
this.purchased= pch;
}
make a new object and pass values
Ticket t1=new Ticket(3,"yourstring","yourstring",yourDouble,true/false);
add items in arrayliSt:
List<Tickets> tList=new ArrayList();
tList.add(t1);
tList.add(t2);
//and so on
now retrive values from arralylist
Ticket t=tlist.get(0);
t.cat;
t.whatevrbe thevalue be
I currently have the following HashMap in a Holiday class.
Holiday Class:
HashMap <String, Location> holidays = new HashMap<String, Location>();
This creates an instance of the Location class, to allow more fields to be shown.
Location class:
public class Location {
private String locationName;
private String locationDesc;
private double price;
private int quantity;
public Location(String locationName, String locationDesc, double price) {
this.locationName = locationName;
this.locationDesc = locationDesc;
this.price = price;
quantity = 0;
}
public String toString() {
return (locationName + " | " + "£" + price);
}
public double getPrice() { return price; }
public String getLocationName() { return locationName; }
public String getLocationDesc() { return locationDesc; }
public int getQuantity() { return quantity; }
}
In my GUI class I just use the .get HashMap method, this will return the toString.
e.g
GUI class
private Holiday holiday;
...
return holiday.holidays.get(--HashMap key here--);
this will return the toString, which is locationName and price.
However. I'm wanting to also print out the HashMap elsewhere, but with returning different fields. such as returning the Description and quantity as well as locationName and price. How would i go about doing this? Or how do i return the individual fields from the Location class which is an instance of in the HashMap.
MANAGED TO DO THIS. But need help with the following below
Second EDIT:
I have a set quantity method in my Location class, to set the amount of bookings for each holiday. However when using;
for (Location location : holiday.holidays.values()) {
location.setQuantity(Integer.parseInt(textFieldQuantity.getText()));
}
This changes all of the holidays to the same quantity when setting each location with a different quantity. How do i fix this?
The result of holidays.get(key) should be an object of type Location. If you print the object directly, like in System.out.println(holidays.get(key)) it will print the result of toString() as you say. But since you already have the object and access to its fields, you can print exactly what you want.
Something like this should work:
Location location = holidays.get(key);
System.out.println(location.getlocationDesc() + " | " + location.getQuantity());
Regarding your second question:
If you just need to print all values stored in your map, I think it would be cleaner and faster to iterate directly on the map values:
for (Location location : holiday.holidays.values()) {
System.out.println(location.getlocationDesc() + " | " + location.getQuantity());
}
Third question:
Note that your code does not set the quantity for only one location. It goes through all locations setting each quantity to the same value, defined by textFieldQuantity.getText().
If you want to modify a specific location, you need to retrieve it from the map using get():
Location location = holiday.holidays.get(key);
location.setQuantity(Integer.parseInt(textFieldQuantity.getText()));
Why not try something like:
private Location location = holiday.holidays.get(--HashMap key here--);
// Create a string with the variables
And then return the string.
this will return the toString, which is locationName and price
No. It will return an instance of Location. So all you have to do is
Location location = holiday.holidays.get("some key");
double price = location.getPrice();
String locationName = location.getLocationName();
Note that
you shouldn't use public fields. So it should be instead location.getHolidays().get("some key"). Or even better, to encapsulate the Map and respect the "don't talk to strangers" rule, location.getHoliday("some key").
Your getter should be named getLocationName() and not getlocationName() to respect the JavaBean conventions. Or even better, since this method is part of a Location class, the location prefix is redundant, and you should thus simply name it getName() (and getDescription() for the description)
I need to have a user type in a sixteen-digit number (without suffixes or quotes) and then pass that number to an object. Whenever I attempt to enter such a number, it is considered "datatype int out of range". I don't want the user to have to enter it as XXXXXXXXXXXXXXXXL, because the user may not know that java requires an L for longs. I also don't want it to require quotes around the numbers. Is there a way to convert this before java throws exceptions regarding datatype mismatch or out of range exceptions?
Can this even be done? I'm trying to construct a Customer object that's a field in an Order object, which itself is within an ArrayList<Order> orderList. "Sam Totman" and the number next to it are examples of the parameters I'm using.
orderList.get(1).setBuyer(new Customer("Sam Totman", 2112112121121121));
What should go where I have placed datatype in this constructor? ccn is credit card number;
public class Customer
{
private String name;
private *datatype* ccn;
Customer(String name, *datatype* ccn)
{
this.name = name;
this.ccn = ccn;
}
orderList.get(1).setBuyer(new Customer("Sam Totman", new Scanner(System.in).nextLong());
Use scanner to handle input
Scanner scan = new Scanner(System.in);
long aLong = scan.nextLong(10);
....
orderList.get(1).setBuyer(new Customer("Sam Totman", aLong));
Customer
public class Customer
{
private String name;
private long ccn;
Customer(String name, long ccn)
{
this.name = name;
this.ccn = ccn;
}
}