You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中从字符串提取Double值的问题及代码优化需求

Fixing Double Value Extraction from Your String

Hey there! I see the issue with your current code—right now, you're only keeping digits (0-9) by replacing everything else, but that strips out decimal points (and would miss negative signs if they were present), so values like 4.5 get mangled into 45 which isn't useful for Double types. Let's fix this with two straightforward solutions.

Why Your Current Code Fails

Your line numbers=str.replaceAll("[^0-9]", "...") uses a regex that only matches digits. But Double values can include:

  • Decimal points (.)
  • Optional negative signs (-)
    So this approach destroys the structure of valid Double numbers.

Solution 1: Use Regex to Match Full Double Values

We can write a regex that specifically targets valid Double formats, then extract and parse each match. Here's the updated code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

public class mine {
    public static void main(String[] args) throws Exception {
        Scanner SC = new Scanner(System.in);
        System.out.print("Enter string that contains numbers: ");
        String str = SC.nextLine();
        
        // Regex to match integers, decimals, and negative Doubles
        Pattern doublePattern = Pattern.compile("-?\\d+\\.?\\d*|\\d*\\.?\\d+");
        Matcher matcher = doublePattern.matcher(str);
        
        System.out.println("Extracted Double values:");
        while (matcher.find()) {
            try {
                double extractedValue = Double.parseDouble(matcher.group());
                System.out.println(extractedValue);
            } catch (NumberFormatException e) {
                // This should rarely happen with our regex, but just in case
                System.out.println("Skipping invalid entry: " + matcher.group());
            }
        }
    }
}

Regex Breakdown

  • -?: Matches an optional negative sign
  • \d+\.?\d*: Matches numbers with an integer part (like 4, 4.5)
  • |: Acts as an OR operator
  • \d*\.?\d+: Matches numbers that start with a decimal (like .5, though this is less common but still valid for Doubles)

Solution 2: Leverage Scanner's Built-in Number Detection

Java's Scanner can automatically recognize numeric values if we set the right delimiter. Instead of writing complex regex, we can tell it to split the string on any character that isn't part of a Double:

import java.util.Scanner;

public class mine {
    public static void main(String[] args) throws Exception {
        Scanner SC = new Scanner(System.in);
        System.out.print("Enter string that contains numbers: ");
        String str = SC.nextLine();
        
        // Split the string on any character that's not a digit, decimal, or negative sign
        Scanner numberScanner = new Scanner(str);
        numberScanner.useDelimiter("[^-0-9.]");
        
        System.out.println("Extracted Double values:");
        while (numberScanner.hasNextDouble()) {
            double extractedValue = numberScanner.nextDouble();
            System.out.println(extractedValue);
        }
        numberScanner.close();
    }
}

How This Works

useDelimiter("[^-0-9.]") sets all non-numeric characters (like parentheses, commas, spaces, semicolons) as separators. The Scanner then uses its built-in logic to pick out valid Double values directly—no manual parsing needed!

Testing with Your Input

If you enter your test string r ( 4.5, 1.0 ) 10.5 7 ;, both solutions will output:

4.5
1.0
10.5
7.0

内容的提问来源于stack exchange,提问作者Pape Traore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:13:04