1
import java.util.*;

class Dis {

    static boolean Digitinstring(String s) {
        boolean result = false;
        int i, j;
        char[] ch = s.toCharArray();
        int x = ch.length;
        for (j = 0; j < x; j++) {

            for (i = 0; i <= 9; i++) {

                if (ch[j] == i) {
                    System.out.println("True");
                    result = true;
                } else {
                    result = false;
                }

            }
        }
        return result;
    }

    public static void main(String args[]) {
        System.out.println("Enter the string");
        Scanner ob = new Scanner(System.in);
        String s = ob.nextLine();
        System.out.println(Digitinstring(s));
    }
}

This code always gives the answer false. The if condition is not working. What can I do to make it work properly?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 1
    Remove `else` part. `ch[j]` contains `char` but `i` is `int`, `'2' == 2` is never true. – Pshemo Sep 05 '15 at 18:07
  • you only want to know if there is digit in string or not right then it is quite simple you dont need to write the nested loop I will upload a working program for the same within few minutes – Piyush Yawalkar Sep 05 '15 at 18:13

6 Answers6

4

Your code is failing because '3' does not equal 3. The character 3, which is your ch[j] will never be equal to an actual integer because they have different types. If you want this to work, you should replace your if condition with this:

Character.getNumericValue(ch[j]) == i;

An easier approach to this would be to simply use

Character.isDigit(s.charAt(j)); 

Your whole method would look like this:

public static boolean digitInString(String s){


    for(int i = 0; i<s.length(); i++){

        if(Character.isDigit(s.charAt(i))){
            return true;
        }


    }
    return false; 

}
ninesalt
  • 4,054
  • 5
  • 35
  • 75
2

You can use regular expressions for more compact code. Regular expressions are good for exactly your scenario, which is looking for specific patterns in Strings. In your Digitinstring you can do the following:

return s.matches(".*\\d.*");

That returns true if your string has any number of characters (.*) followed by a digit (\\d) followed by any number of characters (.*). Any number of characters can include 0.

Swailem95's post well explains why your current implementation is not returning expected results.

Thalador
  • 51
  • 7
1

There are few problems. First is your else block. Remember that in case of if(){1}else{2} one of two blocks must always be executed, either it will be {1} or {2}.
It means that your result will depend only on last test, in other words on last character.
To solve this problem remove else block and let result store true only if your test will find digit.

Second problem is that, in (ch[j] == i) you are comparing char and int. So you are ending up with something like
if ('2' == 2) which is false in Java, because int representation of '2' is its index in Unicode Table, which is 50.

So as you see condition like '2'==2 is same as 50==2 which is false.

To generate all chars containing digits you can simply write for (char digit = '0'; digit<='9'; digit++) like in this code:

static boolean DigitInString(String s) {
    for (char ch : s.toCharArray()) {
        for (char digit = '0'; ch <= '9'; ch++) {
            if (ch == digit) {
                System.out.println("True");
                return true;
            } 
        }
    }
    return false;
}

You can also increase readability of your code and replace this nested loop

        for (char digit = '0'; ch <= '9'; ch++) {
            if (ch == digit) {
                System.out.println("True");
                return true;
            } 
        }

with

        if (Character.isDigit(ch)){
            System.out.println("True");
            return true;
        }

This method will check if character is in range specified for digits characters in Unidoce Table.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1
/* Note: 48 to 57 is ascii values of 0,1, 2,...9 respectively
   code is made more readable ascii values are not used now 
 */
package com;

import java.util.Scanner;

public class Dis {
    public static void main(String[] args) {
        System.out.println("Enter the string");
        Scanner ob = new Scanner(System.in);
        String s = ob.nextLine();
        System.out.println(Digitinstring(s));
        ob.close();
    }

    private static boolean Digitinstring(String s) {
        boolean result = false;
        for (int j = 0; j < s.length(); j++) {
            if(s.charAt(j)>='0' && s.charAt(j)<='9')
           {
               result=true;
               break;
           }
        }
        return result;
    }
}
Piyush Yawalkar
  • 252
  • 1
  • 4
  • 17
  • No need to write nested loops check the above solution and use break statement to avoid extra iterations – Piyush Yawalkar Sep 05 '15 at 18:28
  • 2
    `(int)s.charAt(j)>=48` (1) you don't need casting to `int`, chars can be treated as ints if needed like in this case (2) avoid [magic numbers](http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) - you can rewrite your code as `if (s.charAt(j) >= '0' && s.charAt(j) <= '9')` which is a lot easier to read (or you could use `Characters.isDigit`) – Pshemo Sep 05 '15 at 18:28
  • Thanks Pshemo I have edited my code and please tell me If i can further improve the code – Piyush Yawalkar Sep 05 '15 at 18:34
  • For me your answer looks OK, but you can improve it by adding explanation of why you made your changes if you think OP may need it. – Pshemo Sep 05 '15 at 18:40
0

You have a problem with:

for (i = 0; i <= 9; i++) {
    if (ch[j] == i) {
         System.out.println("True");
         result = true;
    } else {
         result = false;
    }
}

ch[j] is a character and i is a number, so the character '0' has a number value of 46 (if I remember correctly), so you can rectify the situation by adding '0' to i in the if statement

if (ch[j] == i+'0') {

or modifying the for loop

for (i = '0'; i <= '9'; i++) {

notice that the 0 in this case is a character.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Tawcharowsky
  • 615
  • 4
  • 18
0

if (ch[j] == i)

Please correct condition mentioned above to compare same object types, you currently using different types which is never true. Or use inbuilt isDigit method from Character Class.

ravinikam
  • 3,666
  • 6
  • 28
  • 25
  • 1
    "*you currently using different types which is never true*" is not true, `'2'==50` is evaluated to `true` despite different types (`char` and `int`). Problem lies in values, not in types. Having same type simply makes it easier to work with. – Pshemo Sep 05 '15 at 18:47