Results 1 to 2 of 2

Thread: [RESOLVED] I think my while loop is infinite but I'm not seeing where

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    2

    Resolved [RESOLVED] I think my while loop is infinite but I'm not seeing where

    The assignment specifically says to do the while loop to take the reversed phrase and print every other character. I'm compiling fine and my other loops work correctly, but when I run it it gets hung up and doesn't print out anything from the while loop on. I've tried to add in the loop for it to print the index so I could see if it was doing anything but it's not printing out anything unless I put the SOP before the loop. Usually I can find answers by reading previous questions, but I'm comparing this loop to my notes and to things all over the internet and I'm just not seeing it. Thanks in advance for any help.

    Code:
    import java.util.Scanner;
    
    public class StringFun
    {
    	public static void main (String [] args)
    	{	
    	String string, otherString, revString, anotherString;
    	int index;
    	
    	Scanner scan = new Scanner(System.in);
    	
    	System.out.print("Enter a string: ");
    	string = scan.nextLine();
    	index = 0;
    	otherString = "";
    	revString = "";
    	anotherString = "";
    	
    	do
    	{
    		otherString = otherString +string.charAt(index);
    		index=index+2;
    	}
    	while (index<string.length());
    	
    	System.out.println ("The string '" +string+ "' printing only every other letter is '" +otherString+"'.");
    	
    	for(index=string.length()-1;index>=0;index--)
    		{revString = revString +string.charAt(index);}
    	
    	System.out.println ("The string '" +string+ "' reversed is '" +revString+"'.");
    
    	
    	index=0;
    	while (index<=revString.length());
    		{
    		anotherString = anotherString + revString.charAt(index); 	
    		index=index+2;
    		}
    		
    	System.out.println ("The string '" +revString+ "' printing only every other letter is '" +anotherString+"'.");
    	
    	}
    }

  2. #2

    Thread Starter
    New Member
    Join Date
    Jan 2012
    Posts
    2

    Re: I think my while loop is infinite but I'm not seeing where

    Well it turns out that all I needed was a few hours of sleep and then I erased the old loop and started another one and it worked. I'll assume that anyone who reads this is looking for the solution so here is how I rewrote the loop to make it print every other character of the reversed string,

    Code:
    	index=0;
    	while(index<=revString.length()-1)
    	{
    		anotherString = anotherString +revString.charAt(index);
    		index=index+2;
    	}

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width