Java 是否有其他可能将字符串转换为双精度?

Java 是否有其他可能将字符串转换为双精度?,java,Java,我正在学习Java,在我的一个名为“销售点”的项目中遇到了一个问题。当程序从用户处读取条形码时,它开始在products.txt中搜索正确的产品。当它找到产品时,接下来它应该为创建的对象设置值。当我尝试将字符串转换为double时,就会出现问题。我花了将近两个小时来解决这个问题,但没有成功。我需要你的帮助 所以我试过: double dbl = Double.valueOf(parts[2]); p.set_price(dbl); 还尝试了这样的组合(但不起作用): 只有一种方法 publi

我正在学习Java,在我的一个名为“销售点”的项目中遇到了一个问题。当程序从用户处读取条形码时,它开始在products.txt中搜索正确的产品。当它找到产品时,接下来它应该为创建的对象设置值。当我尝试将字符串转换为double时,就会出现问题。我花了将近两个小时来解决这个问题,但没有成功。我需要你的帮助

所以我试过:

double dbl = Double.valueOf(parts[2]);
p.set_price(dbl); 
还尝试了这样的组合(但不起作用):

只有一种方法

public void newSale() { 
    Products p = new Products();

    // Barcode
    System.out.print("Barcode:");
    p.set_barcode(scan.next());

    // Find the product
    try{
    File file = new File("products.txt");
    Scanner scan = new Scanner(file);

    while(scan.hasNextLine()) {
        String x = scan.next();
        if(x.contains(p.get_barcode())) {
            String[] parts = x.split(";");
            p.set_barcode(parts[0]);
            p.set_name(parts[1]);
            try{
                double dbl = Double.valueOf(parts[2]);
                p.set_price(dbl);
            }catch(NumberFormatException ex){
                System.err.println("Error: " + ex.getMessage());
            }

        }               
    }            
    }catch(Exception e){
        System.err.println("Error: " + e.getMessage());
    }
    System.out.print(p.get_name()+"\t"+p.get_price());
}   

如果有人能帮助我理解为什么转换和赋值不起作用,那就太好了。

Dot将整数和分数分隔成双精度。在products.txt中,将价格中的逗号改为点。这应该会有帮助:)

请定义“不工作”。您遇到了什么错误?在您的文件中,第一行是
条形码;名称价格
所以指数
2
处的值是
Price
,不能转换成双精度,下一行也是
0101;波马兰策;4,36
其中索引
2
处的值为
4,36
或者您无法将其转换为您认为需要其他解决方案的原因?是的,您需要
DecimalFormat
类。可以将逗号解释为十进制分隔符。谢谢您的评论。问题是在txt文件中,我应该使用点而不是逗号。是的,这很有帮助,谢谢!:)
double dbl = new Double(parts[2]);
p.set_price(dbl);
p.set_price(Double.valueOf(parts[2].ToString()));
public void newSale() { 
    Products p = new Products();

    // Barcode
    System.out.print("Barcode:");
    p.set_barcode(scan.next());

    // Find the product
    try{
    File file = new File("products.txt");
    Scanner scan = new Scanner(file);

    while(scan.hasNextLine()) {
        String x = scan.next();
        if(x.contains(p.get_barcode())) {
            String[] parts = x.split(";");
            p.set_barcode(parts[0]);
            p.set_name(parts[1]);
            try{
                double dbl = Double.valueOf(parts[2]);
                p.set_price(dbl);
            }catch(NumberFormatException ex){
                System.err.println("Error: " + ex.getMessage());
            }

        }               
    }            
    }catch(Exception e){
        System.err.println("Error: " + e.getMessage());
    }
    System.out.print(p.get_name()+"\t"+p.get_price());
}