while loop with a decrementing counter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tolkienarda
    Contributor
    • Dec 2006
    • 316

    while loop with a decrementing counter

    hi all
    i have a with my counter that starts at a value then for each step through the loop it should go down by one. ok the trial data i have when i run this program, and i have checked and rechecked it to make sure that the test data has the expected values

    i=3
    revline[0]=a
    [1]=s
    [2]=d
    [3]=f
    Code:
        		System.out.println(i);
    	    	while(i>=0)
    	    	{
    	    		System.out.print(revline[i]);
    	    		i--;
    	    		System.out.print(i);
    	    	}
    output:
    3

    Process completed.
    if I move the second System.out.prin t(i); above the i--; then it will print a 3 so I think that the i--; line is incorect but I tried i = i - 1; and that didn't work either so I am at a total loss, the remainder of my code is below,
    this is a homework assignment and I am not trying to cheat just figure out my error, anyway the assignment is to get a string from a user then print it reversed

    Code:
    /**
     * @(#)asg5.java
     *
     * asg5 application
     *;
     * @author 
     * @version 1.00 2007/9/24
     */
     import java.util.*;
    public class asg5 {
        static Scanner console = new Scanner(System.in);
        public static void main(String[] args) {
        	String line;
        	Boolean rev;
        	System.out.println("Enter a line of text 'q' to exit");
        	line = console.nextLine();
        	rev = recRev(line, 0);
        	
        	
        }
        public static Boolean recRev(String line, int pos){
        	int length, i;
        	char[] revline = new char[50];
        	length = line.length();
        	i=length - 1;
    		
        	if (length>50)
        	{
        		return false;
        	}
        	if (pos<length)
        	{
        		revline[pos] = line.charAt(pos);
        		pos = pos + 1;
        		recRev(line, pos);
        	}else{
        		System.out.println(i);
    	    	while(i>=0)
    	    	{
    	    		System.out.print(revline[i]);
    	    		i--;
    	    		System.out.print(i);
    	    	}
        	}
        	return true; 
        }
    }
    thanks
    eric
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Originally posted by tolkienarda
    hi all
    i have a with my counter that starts at a value then for each step through the loop it should go down by one. ok the trial data i have when i run this program, and i have checked and rechecked it to make sure that the test data has the expected values

    i=3
    revline[0]=a
    [1]=s
    [2]=d
    [3]=f
    Code:
        		System.out.println(i);
    	    	while(i>=0)
    	    	{
    	    		System.out.print(revline[i]);
    	    		i--;
    	    		System.out.print(i);
    	    	}
    output:
    3

    Process completed.
    if I move the second System.out.prin t(i); above the i--; then it will print a 3 so I think that the i--; line is incorect but I tried i = i - 1; and that didn't work either so I am at a total loss, the remainder of my code is below,
    this is a homework assignment and I am not trying to cheat just figure out my error, anyway the assignment is to get a string from a user then print it reversed

    Code:
    /**
     * @(#)asg5.java
     *
     * asg5 application
     *;
     * @author 
     * @version 1.00 2007/9/24
     */
     import java.util.*;
    public class asg5 {
        static Scanner console = new Scanner(System.in);
        public static void main(String[] args) {
        	String line;
        	Boolean rev;
        	System.out.println("Enter a line of text 'q' to exit");
        	line = console.nextLine();
        	rev = recRev(line, 0);
        	
        	
        }
        public static Boolean recRev(String line, int pos){
        	int length, i;
        	char[] revline = new char[50];
        	length = line.length();
        	i=length - 1;
    		
        	if (length>50)
        	{
        		return false;
        	}
        	if (pos<length)
        	{
        		revline[pos] = line.charAt(pos);
        		pos = pos + 1;
        		recRev(line, pos);
        	}else{
        		System.out.println(i);
    	    	while(i>=0)
    	    	{
    	    		System.out.print(revline[i]);
    	    		i--;
    	    		System.out.print(i);
    	    	}
        	}
        	return true; 
        }
    }
    thanks
    eric
    Hi Eric!

    I can't see the error in your code right now, but normally for that sort of job you'd use a for-loop like this:
    [CODE=java]
    for(int i=0; i>=0; i--) // if you want to define i before, use for(; i>=0; i--)
    {
    // ...
    }
    [/CODE]Also, why don't you create the char array with exactly the same amount of chars as the String has?

    Greetings,
    Nepomuk

    Comment

    • stack
      New Member
      • Sep 2007
      • 40

      #3
      Nepomuk is right!

      Just create an array of chars and then store in it all the chars
      of the string that the user enters. Then the only thing left is to print
      the array on the screen but starting from the last position.
      You 'll save yourself from a lot of typing :-)))

      Cheers

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        Originally posted by stack
        Just create an array of chars and then store in it all the chars
        of the string that the user enters.
        Read the String API to find methods, that will be very useful doing that job.

        Greetings,
        Nepomuk

        Comment

        • tolkienarda
          Contributor
          • Dec 2006
          • 316

          #5
          thanks you guys

          here is how i finaly did it
          Code:
           import java.util.*;
          public class asg5 {
          	
              static Scanner console = new Scanner(System.in);
              public static void main(String[] args) {
              	String line;
              	String again;
              	Boolean rev;
              	int length;
              	int i;
              	System.out.println("Enter a line of text");
              	line = console.nextLine();
              	length = line.length();
              	i=length - 1;
              	rev = recRev(line, i);
          
              	
              	
              }
              public static Boolean recRev(String line, int i){  
              	if (i>=0)
              	{
              		System.out.print(line.charAt(i));
          	    	i--;
              		recRev(line, i);
              	}
              	return true;
              }
          }
          i read the problem from my textbook again and all it says is use a recursive function to print it backward and so i did
          but now i am having a new problem. i want to ask the user if they want to do it over again. so my plan was to ask the user and if they enter yes recall the main() function, i am having some problems with my if statement not sure what is wrong with it but if one of you could take a look that would be helpful

          the below code is located at the end of my main() function.
          when i print the again var it prints a y but then won't go into my if statement
          Code:
                  String again;
              	System.out.println("\n would you like to go again(y/n)");
              	again = console.next();
              	System.out.println(again);
              	if(again == "y")
              	{
              		System.out.println("i cant get here");
              		main(args);
              	}
          When i comment the if statement and the curly braces it prints the "i cant get here" and recalls the function but won't allow me to enter more text. it just reprints the
          Enter a line of text
          then the
          would you like to go again(y/n)
          and it will allow me to input here and when i do it prints
          i cant get here
          then starts over again

          here is all of the code together with the if statement not commented out

          thanks for all the help
          Code:
          /**
           * @(#)asg5.java
           *
           * asg5 application
           *;
           * @author 
           * @version 1.00 2007/9/24
           */
           import java.util.*;
          public class asg5 {
          	
              static Scanner console = new Scanner(System.in);
              public static void main(String[] args) {
              	
              	String line;
              	String again;
              	Boolean rev;
              	int length;
              	int i;
              	System.out.println("Enter a line of text");
              	line = console.nextLine();
              	length = line.length();
              	i=length - 1;
              	rev = recRev(line, i);
              	System.out.println("\n would you like to go again(y/n)");
              	again = console.next();
              	System.out.println(again);
             		if (again == "y")
              	{
              		System.out.println("i cant get here");
              		main(args);
              	}
              	
              	
              }
              public static Boolean recRev(String line, int i){  
              	if (i>=0)
              	{
              		System.out.print(line.charAt(i));
          	    	i--;
              		recRev(line, i);
              	}
              	return true;
              }
          }
          eric

          Comment

          • tolkienarda
            Contributor
            • Dec 2006
            • 316

            #6
            ok so i just figured out why my if didn't work i needed the str.equals("y") function. and i kinda gave up on the recursive main function though i would still like to know if it works. anyway i put my code below the declarations into a loop and it works except i am having the save problem that i can't reinput my line variable, not sure why. if any one knows it would be helpful, i read the scanner class documentation and couldn't find anything about it in there, the part that confuses me the most is that it allows me to input the again variable.

            thanks for any ideas or comments

            eric

            Comment

            • Nepomuk
              Recognized Expert Specialist
              • Aug 2007
              • 3111

              #7
              Originally posted by tolkienarda
              ok so i just figured out why my if didn't work i needed the str.equals("y") function. and i kinda gave up on the recursive main function though i would still like to know if it works. anyway i put my code below the declarations into a loop and it works except i am having the save problem that i can't reinput my line variable, not sure why. if any one knows it would be helpful, i read the scanner class documentation and couldn't find anything about it in there, the part that confuses me the most is that it allows me to input the again variable.

              thanks for any ideas or comments

              eric
              Well done for figuring out the problem yourself! I do however have a recommendation, that will make things easier:

              Whenever you want to have something, that should (may) be used more than once, write an own method for it. That makes it much easier to repeat everything - you could have something like this:
              [CODE=java]
              boolean continue = false;
              do
              {
              recursiveFuncti on(args);
              System.out.prin tln("Again?");
              if(scanner.next ().equals("y"))
              continue = true;
              } while(continue)
              [/CODE]That should also allow you to reset all values that aren't final (including the line variable I hope).

              Greetings,
              Nepomuk

              Comment

              • r035198x
                MVP
                • Sep 2006
                • 13225

                #8
                Originally posted by nepomuk
                Well done for figuring out the problem yourself! I do however have a recommendation, that will make things easier:

                Whenever you want to have something, that should (may) be used more than once, write an own method for it. That makes it much easier to repeat everything - you could have something like this:
                [CODE=java]
                boolean continue = false;
                do
                {
                recursiveFuncti on(args);
                System.out.prin tln("Again?");
                if(scanner.next ().equals("y"))
                continue = true;
                } while(continue)
                [/CODE]That should also allow you to reset all values that aren't final (including the line variable I hope).

                Greetings,
                Nepomuk
                Except that continue is a keyword so the compiler won't like any of that.

                Comment

                • Nepomuk
                  Recognized Expert Specialist
                  • Aug 2007
                  • 3111

                  #9
                  Originally posted by r035198x
                  Except that continue is a keyword so the compiler won't like any of that.
                  Ah, true, then call the boolean "continueWithWh ateverYouAreDoi ng" or "dontStop" or something like that. But year, continue is a codeword... which makes me think of being evil and doing it like this:
                  [CODE=java]
                  while(true)
                  {
                  recursiveFuncti on(args);
                  if(scanner.next ().equals("y") continue;
                  break;
                  }
                  [/CODE]which looks pretty awful, I find. (But it should work! ^^)

                  Greetings,
                  Nepomuk

                  Comment

                  • tolkienarda
                    Contributor
                    • Dec 2006
                    • 316

                    #10
                    thank you all for your help just one more quick question

                    is it possible to recall the main() function
                    i don't need it for this program but it may be useful sometime in the future

                    eric

                    Comment

                    • r035198x
                      MVP
                      • Sep 2006
                      • 13225

                      #11
                      Originally posted by tolkienarda
                      thank you all for your help just one more quick question

                      is it possible to recall the main() function
                      i don't need it for this program but it may be useful sometime in the future

                      eric
                      Don't try to do that at all. Always look for an alternative design.

                      Comment

                      • tolkienarda
                        Contributor
                        • Dec 2006
                        • 316

                        #12
                        hmm i am still having a problem
                        i still cannot input my string that is to be reversed.
                        and my loop appears to be infinite, i am not sure if that semi colon behind my while statement is correct but i got build errors without it
                        here is my entire main() function

                        Code:
                            public static void main(String[] args) {
                            	
                            	String line;
                            	Boolean cont = false;
                            	Boolean rev;
                            	int length;
                            	int i;
                            	do
                            	{
                        	    	System.out.println("Enter a line of text");
                        	    	line = console.nextLine();
                        	    	length = line.length();
                        	    	i=length - 1;
                        	    	rev = recRev(line, i);
                        	    	System.out.println("\n would you like to go again(y/n)");
                        	    	if(console.next().equals("y"))
                        	    		cont = true;
                            	} while(cont);
                            }
                        Output
                        [CODE]
                        Enter a line of text
                        asdf
                        fdsa
                        would you like to go again(y/n)
                        y
                        Enter a line of text

                        would you like to go again(y/n)
                        n
                        Enter a line of text

                        would you like to go again(y/n)
                        [CODE]

                        and there is no pause for me to input text after the "Enter a line of text" line it just prints the " would you like to go again(y/n)"

                        eric

                        Comment

                        • tolkienarda
                          Contributor
                          • Dec 2006
                          • 316

                          #13
                          Originally posted by r035198x
                          Don't try to do that at all. Always look for an alternative design.
                          Ok

                          thanks
                          eric

                          Comment

                          • JosAH
                            Recognized Expert MVP
                            • Mar 2007
                            • 11453

                            #14
                            Originally posted by nepomuk
                            [CODE=java]
                            while(true)
                            {
                            recursiveFuncti on(args);
                            if(scanner.next ().equals("y") continue;
                            break;
                            }
                            [/CODE]which looks pretty awful, I find. (But it should work! ^^)
                            Duh;

                            [code=java]
                            do {
                            recursiveFuncti on(args);
                            }
                            while (scanner.next() .equals("y"));
                            [/code]

                            kind regards,

                            Jos

                            Comment

                            • Nepomuk
                              Recognized Expert Specialist
                              • Aug 2007
                              • 3111

                              #15
                              Originally posted by JosAH
                              Duh;

                              [code=java]
                              do {
                              recursiveFuncti on(args);
                              }
                              while (scanner.next() .equals("y"));
                              [/code]

                              kind regards,

                              Jos
                              Year, but that doesn't contain continue! ^^

                              Comment

                              Working...