Here is what I have so far...

import java.util.Scanner;

public class tst
{
  public static void main (String [] args)
  {
	  Scanner stdIn = new Scanner(System.in);
      String sentence = "This is the test.";
      char response;            // user's y/n response

      int ctr = 65;

	      do
	  	  {
			System.out.print ("Would you like to see a do-while loop execute? (y/n): ");
            for(ctr = 0; ctr < sentence.length(); ctr++);
            {
		      System.out.println(sentence.charAt(ctr));
		    }

            response = stdIn.next().charAt(0);

          } while (response == 'y' || response == 'Y');




  } // end main
} // end class tst

I'm trying to get the program to print out the value of sentence one character per line using the for loop within the do-while loop after the user answers y or Y to the query.
Please help. I appreciate the help in advance.

EDIT: I tried to switch the response input below the question presented to the user and when I run the Java Application I get prompted with the question but run into a mess when I answer y.

First, use code tags. Press the button CODE and put your code between the tags.
Also I tried running your code and it didn't work, even though it is correct. It behaves very strange and the debug gives me strange behavior. Finally I found the problem. When you write (me) something a lot of times, when you see it written you assume that it is correct, but in your case it is wrong:

I write:

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

}

You wrote:

for(ctr = 0; ctr < sentence.length(); ctr++);
{

}

Can you spot the difference:

for(ctr = 0; ctr < sentence.length(); ctr++);

We use the ';' to terminate commands. So when you put the ';' at that place you terminated the for loop. So only this got executed N times:

for(ctr = 0; ctr < sentence.length(); ctr++);

And then after ctr changed frm 0 to sentence.length() the following command executed outside the loop:

System.out.println(sentence.charAt(ctr));

So basically when you put that ';' at the end of the for loop you practically wrote something like this:

for(ctr = 0; ctr < sentence.length(); ctr++) {}
{
  System.out.println(sentence.charAt(ctr));
}

The for executes with no body. Then when the ctr is equals to sentence.length() exits the loop and executes one System.out.println(sentence.charAt(ctr)) which gives you an error.

Try running this and see what happens:

int i=0;
for (i=0;i<length;i++);
 System.out.println("i: "+i);

Then write this with no ';'

int i=0;
for (i=0;i<length;i++)
 System.out.println("i: "+i);
commented: Helpful explanation. +15

It runs perfectly! Exactly how I wanted it to. Thank you so much. I actually understand what was wrong rather than copying down what you put.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.