如何用Java中的BigDecimal,String和LocalDate处理这些问题?

时间:2017-10-18 03:31:08

标签: java

我目前正在接受以下异常。问题出在Price类的构造函数部分。我该如何处理这个问题。我应该能够将价格2.29和日期10202017作为字符串

传递
Price price = new Price("2.29", "10/20/2017");

但Price类应该有

private BigDecimal price;
private LocalDate effectiveDate;

我对转换没有好转。谁能告诉我如何实现这一目标并指导我。

理想的输出:

货号:1货号:土耳其三明治分类:杂货UPC:1001价格:2.29

错误

Exception in thread "main" java.time.format.DateTimeParseException: Text '10/20/2017' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDate.parse(Unknown Source)
    at java.time.LocalDate.parse(Unknown Source)
    at posPD.Price.<init>(Price.java:35)
    at posTest.MainTest.main(MainTest.java:27)

主要班级

package posTest;

import java.math.BigDecimal;

import posPD.*;

public class MainTest {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Store myStore = new Store("1", "My Store 1");

        TaxCategory taxCategory1 = new TaxCategory("Beverages");
        TaxCategory taxCategory2 = new TaxCategory("Grocery");

        Register register1 = new Register("Register 1");
        Register register2 = new Register("Register 2");

        Person person1 = new Person("David", "OK" ,"405000000",  "800-800-1000");
        Person person2 = new Person("Sally", "Ktm", "123456789", "000-000-0000");


        Item item = new Item("1", "Turkey Sandwich");


        Price price = new Price("2.029", "10/20/2017");

        UPC upc = new UPC("1001");
        //Price price = new Price("1.49", "2005");

        //Session session = new Session();
        try {


        //CashDrawer cashDraw1 = new CashDrawer(1, BigDecimal.valueOf(500));

        //System.out.println(cashDraw1);
        //System.out.println(register.toString());

        Cashier cashier1 = new Cashier("1", person1 , "Password1");
        //person1.setCashier(cashier1);
        //myStore.addCashier(cashier);
        Cashier cashier2 = new Cashier("1", person2 , "Password1");
        person1.setCashier(cashier1);
        person2.setCashier(cashier2);

        myStore.addCashier(cashier1);

        myStore.addCashier(cashier2);




        //CashDrawer cashDrawer1 = new CashDrawer("Drawer 1.");
        CashDrawer cashDrawer1 = new CashDrawer(1, BigDecimal.valueOf(500));
        CashDrawer cashDrawer2 = new CashDrawer(2, BigDecimal.valueOf(500));

        myStore.addRegister(register1);
        myStore.addRegister(register2);
        register1.setCashDrawer(cashDrawer1);
        register2.setCashDrawer(cashDrawer2);

        //myStore.addTaxCategory(taxCategory1);
        //myStore.addTaxCategory(taxCategory2);

        Session session1 = new Session(cashier1, register1);
        Session session2 = new Session(cashier2, register2);

        myStore.addSession(session1);
        myStore.addSession(session2);

        myStore.addItem(item);
        //myStore.addUPC(upc);
        item.addUPC(upc);

        //item.addPrice(price);
        item.setTaxCategory(taxCategory2);




        //myStore.addCashier(cashier2);

        SaleLineItem sli = new SaleLineItem();

        System.out.println("=========");
        System.out.println( " "+myStore);
        System.out.println("=========");



        } catch(Exception e) {System.out.println("Exception exists");}

    }

}

价格等级

package posPD;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Price details
 */
public class Price {

    private BigDecimal price;
    private LocalDate effectiveDate;
    private Item item;

    public Price() {
        // TODO - implement Price.Price
        //throw new UnsupportedOperationException();

    }

    /**
     * 
     * @param price
     * @param effectiveDate
     */
    public Price(String price, String effectiveDate) {
        // TODO - implement Price.Price
        //throw new UnsupportedOperationException();
        this();
        BigDecimal bdprice = new BigDecimal (price);
        this.price = bdprice;

        LocalDate dt = LocalDate.parse(effectiveDate);
        this.setEffectiveDate(dt);

    }

    /**
     * 
     * @param date
     */
    public Boolean isEffective(LocalDate date) {
        // TODO - implement Price.isEffective


        throw new UnsupportedOperationException();
        /*
        if (LocalDate.now().isAfter(date)) {
            return false;
        }
        return true;
        */

    }

    /**
     * 
     * @param quantity
     */
    public BigDecimal calcAmountForQty(int quantity) {
        // TODO - implement Price.calcAmountForQty
        //throw new UnsupportedOperationException();

        return price;
    }

    /**
     * 
     * @param date
     */
    /*
    public Boolean isPriceEffectiveForDate(LocalDate date) {
        // TODO - implement Price.isPriceEffectiveForDate
        throw new UnsupportedOperationException();
    }
    */

    /**
     * 
     * @param price
     */
    public void compareTo(Price price) {
        // TODO - implement Price.compareTo
        throw new UnsupportedOperationException();

    }

    public String toString() {
        // TODO - implement Price.toString
        throw new UnsupportedOperationException();
        //return 
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    public LocalDate getEffectiveDate() {
        return effectiveDate;
    }

    public void setEffectiveDate(LocalDate effectiveDate) {
        this.effectiveDate = effectiveDate;
    }

}

3 个答案:

答案 0 :(得分:1)

您使用的LocalDate.parse的一个参数版本需要此格式的CharSequence(&#34; yyyy-MM-dd&#34;)。您可以通过这种方式格式化日期,例如

void main(){
    struct stat time_buf;
    time_t input_timestamp=0;

    while(1){
        if(access( "inpfile.txt", F_OK ) != -1){
            sleep(5);
            stat("inpfile.txt", &time_buf);
            if(time_buf.st_mtime > input_timestamp){
                FILE *fpi,*fpo;
                long length;
                char *buffer=0;           
                fpi = fopen("inpfile.txt","r");
                fseek(fpi,0,SEEK_END);
                length=ftell(fpi);
                fseek(fpi,0,SEEK_SET);
                buffer=(char *)malloc(length);
                fread(buffer,1,length,fpi);
                fclose(fpi);      

                fpo=fopen("outfile.txt","w+");
                fwrite(buffer,sizeof(char),length,fpo);
                fclose(fpo);
                input_timestamp=time_buf.st_mtime;
            }
        }
    }

}

最好通过使用这样的DateTimeFormatter来支持您使用的String格式(&#34; 10/20 / 2017&#34;):

Price price = new Price("2.29", "2017-10-20");

[编辑以根据您的评论添加测试示例]:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate dt = LocalDate.parse(effectiveDate, formatter);

对我来说,这输出以下内容没有错误:

    String input1 = "2017-10-20";
    LocalDate date1 = LocalDate.parse(input1);
    System.out.println("Using no formatter    input1["+input1+"]  date1 ["+date1+"]");

    String input2 = "10/20/2017";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate date2 = LocalDate.parse(input2, formatter);
    System.out.println("Formatter MM/dd/yyyy  input2["+input2+"]  date2 ["+date2+"]");

答案 1 :(得分:1)

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate dt = LocalDate.parse(effectiveDate, dtf);

答案 2 :(得分:1)

看看你得到的例外 -

Exception in thread "main" java.time.format.DateTimeParseException: Text '10/20/2017' could not be parsed at index 0.

您以MM / dd / yyyy格式提供日期,但在LocalDate类中,您无法指定格式,因此请更改您的代码,如

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate date = LocalDate.parse(effectiveDate, format);