4 Replies Latest reply on Apr 30, 2013 12:24 PM by 1005446

    for and while loops

      Hello , im new to java, and now i have an assignment. I have to parse a phone number like this--> (656) 345 6544 to 6563456544. I've writen the following code that works great with a while loop. Now i would like to know how can i make it work with a for loop.

      and the code is
      import java.io.*;
      public class Tema
        public static String removeChar(String str, int i)
          String first= str.substring(0,i);
          String last= str.substring(i+1,str.length());
          return str;
        public static String cautaTrimite(String str)
           /*for(int i=0; i<str.length(); i++)
             if ((str.charAt(i)==' ')  ||(str.charAt(i)=='5')  ||(str.charAt(i)=='(')
                ||(str.charAt(i)==')') ||(str.charAt(i)=='-'))
                str = removeChar(str,i);
             int i=0;
                   if(( str.charAt(i)== ' ' )||( str.charAt(i)== '8' )
              str = removeChar(str,i);
        return str;}
        public static void main (String [] args)
           BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
           System.out.println("Introduceti un numar de telefon oarecare: ");
           String str= in.readLine();
           str= cautaTrimite(str);
        catch(IOException e){System.out.println("S-a produs o eroare de IO");}
      Edited by: 1002443 on 30-abr-2013 5:17
        • 1. Re: for and while loops
          Okay, what's stopping you from learning how for loops work? I hope you have a good book on the Java language right next to you, otherwise your first order of business is to get one. But until you do, you might want to try the java tutorial:

          • 2. Re: for and while loops
            Why are you stripping out '8'?
            Just out of curiosity...
            • 3. Re: for and while loops
              In the while loop, you have full control on when you increment the i and when not and what you do is correct.
              Doing this with the for loop always increments the i. To avoid this, you may find out that when you removeChar, you have to decrement the i, just to be incremented by the loop right after.
              All this would result in more obscure code than the while loop, therefore I would not use it.

              Edit: Why you remove 8 in the while loop and 5 in the for loop remains a big mystery.

              Edited by: baftos on Apr 25, 2013 11:56 AM
              • 4. Re: for and while loops
                Many thanks baftos, didn't realize that i had to decrement i.
                The 8 i remove it for fun, not for a special reason.
                Many thanks again.