loop through a string in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • willy131287
    New Member
    • Mar 2007
    • 1

    loop through a string in java

    Hi,

    I am trying to check whether a user inputs a number in a string with letters but every time i check this it only says there is a number if it is at the beginning of the string, otherwise it says there is no number and I was wondering if anyone could help. My code for this is below:

    public void print()
    {
    if(number == false)
    {
    System.out.prin t("there is no number");
    }
    else if (number == true)
    {
    System.out.prin t("number");
    }
    }

    boolean number = false;

    public boolean number(String user)
    {
    for (int i=0; i<user.length() ;i++)
    {
    if ((user.charAt(i ))>=45 && (user.charAt(i) )<=57)
    {
    number = true;
    return true;
    }
    else if(!((user.char At(i))>=45 && (user.charAt(i) )<=57))
    {
    i++;
    //number = true;
    //return true;
    }
    }
    number=false;
    return false;
    }
  • DeMan
    Top Contributor
    • Nov 2006
    • 1799

    #2
    Not quite sure about this code (see attached comments)
    Code:
    public boolean number(String user)
    {
      number =false;  /* Let's initialise to the failure case */
      for (int i=0; i<user.length();i++)
      { 
        if ((user.charAt(i))>=45 && (user.charAt(i))<=57) /* I assume you want basic cal fun as well*/
        {
          number = true;
          return true; /* Get rid of this retunr I think, although you could break if you
                           just need to know whether there was a number, but aren't 
                            interested in how many  *./
        }
        else if(!((user.charAt(i))>=45 && (user.charAt(i))<=57)) /* You could use a simple else since the condition is the total opposite of befroe (that uis the if here is redundant) 
      You may bnot need these else clause anyway*/
        {
          i++; /* I'm not sure why you increment this here */
         //number = true;
        //return true;
    }
    }
    //number=false; /* Set this to false at the beginning, and it will only be true if it found a number */
    return number;
    }

    Comment

    • Eric Geiger
      New Member
      • Mar 2011
      • 1

      #3
      public static boolean number(String user)
      {
      boolean number = false;/*you can get rid of this*/

      for (int i=0; i<user.length() ;i++)
      {
      if (user.charAt(i) >=45 && user.charAt(i)< =57)
      {
      number = true;
      return true;/*2 choices you can either a or 1 do return number or b or 2 just get rid of above statement "number = true"*/
      }
      else if(!(user.charA t(i)>=45 && user.charAt(i)< =57))
      {
      }
      }
      return false;
      }

      Comment

      Working...