Hello...can someone just give me a hint or steps how to trap numbers in String Like in names.I have to make my project in java with traping numbers in names..

Dani AI

Generated

asked about "trapping" numbers in strings; asked for clarity, and pointed out basic string/number conversion. For real input validation or extraction you will want slightly more robust tools than single-character tricks.

For simple validation (reject a name if it contains any digit) a quick regex check is concise:

if (name.matches(".*\\d.*")) {
    // contains at least one digit -> reject
}

To collect digits found inside a string (preserving order), iterate and test each character with a Unicode-aware check:

StringBuilder digits = new StringBuilder();
for (char c : input.toCharArray()) {
    if (Character.isDigit(c)) {
        digits.append(c);
    }
}
String foundDigits = digits.length() > 0 ? digits.toString() : null;

To extract full numeric tokens (multi-digit, optional sign or decimal) use a compiled Pattern and Matcher. Compile once if you run many checks:

Pattern p = Pattern.compile("-?\\d+(?:\\.\\d+)?");
Matcher m = p.matcher(input);
while (m.find()) {
    String token = m.group();
    // convert token to number using standard parsing with exception handling
}

Notes: prefer whitelisting allowed characters for names (letters, spaces, accents) rather than only checking for digits when possible. Use Character.isDigit for Unicode safety. When converting extracted strings to numeric types always handle number-format exceptions and consider locale (decimal separator) and thousands separators if relevant.

Recommended Answers

All 2 Replies

What do you mean by "trap" numbers?

Question is a little vague, but I think you mean:

int x=5;
String y=""+x;

So y is "5"

To reverse this, you could grab the character...

int x=y.charAt(0);

then subtract 48, but that assumes you have a digit 0-9 in the first place.

Much better is:

int x=Integer.parseInt("5");

Hope that helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.