Problem with printing every other letter. Please help
Let me first give you the requirements and then I'll show you my code:
In the main method of this class file, create a string called sentence and assign it a word or sentence of your choice. The rest of the assignment involves working with the contents of this sentence. You should test and ensure that your program works with sentences of different lengths and characters (letters/numbers/special characters).
We will use this sentence as a password starting phrase to automatically create a new password as follows.
<10>Task 1. Create a new string called passwd formed by concatenating every alternate non-space character in sentence starting with the first. To do this, you need to a loop to go through the string sentence and retrieve characters from alternate index positions.
String sentence = "B@n@n@ nut";
System.out.println("The starting sentence is:"+sentence);
for(int i=0; i<sentence.length(); i+=2){
System.out.print(sentence.charAt(i));
So this prints out to:....
The starting sentence is: B@n@n@ nut
Bnn u
I'm not sure if i'm doing it right with the code I am using. I also do not know how to get "The password is:" before the "Bnn u" part. If I put System.out.print("The password is:"+sentence.charAt(i)) then i get...
The password is: B The password is:n The password is:n The password is: The password is:u
I only want it to show "The password is:" once. If anyone could go over the requirements and tell me how to alter my code to make it work I would greatly appreciate it!! Thanks
Re: Problem with printing every other letter. Please help
You need to build the new String up before printing it to the console.
So your loop should (as it says in the task) be concatenating alternate letters together, in another String.
Re: Problem with printing every other letter. Please help
Thanks for the reply. How do I build the string up? I'm very new to java.
Re: Problem with printing every other letter. Please help
See the section in this tutorial on concatenating Strings.
Re: Problem with printing every other letter. Please help
Quote:
Originally Posted by
Tolls
I've been looking at that but am not sure if what I need is an array...
Re: Problem with printing every other letter. Please help
you always need to type in System.out.print(sentence.charAt(i)); in different line. Because the plus sign treats it as a single sentence so reiterates it everytime.
Re: Problem with printing every other letter. Please help
Quote:
Originally Posted by
codec
I've been looking at that but am not sure if what I need is an array...
No you don't.
That page describes concatenation.
There is a section halfway down titled "Concatenating Strings".
Nowhere in that section does it talk about arrays.
It mentions the String.append() method and using '+', the latter being the most common way of doing it.
Now, what do you not understand about that?