1
    public class newString {
   public static void main (String args[]){
      String title = "Book";
      String title1;
      title1 = title;

      for(int i = 0; i < title.length(); i++){
         for (int x = 0; x<title1.length(); x++){
            if (title.charAt(i+x) == title1.charAt(x)){
               System.out.print(title.charAt(0,1));
            }
         }
      }
   }
}

I really don't understand what I'm doing wrong here. What I need to do is define a string called "title", with "Book" in it, which I did, and create a second string called "title1". I need to create code to store the contents of title, into title1, but only every other character. For example: title1 should have "Bo" in it. What am I doing wrong?

JasonBreen
  • 31
  • 1
  • 2
  • 9

3 Answers3

5

Here's the looping solution with fewer operations. Instead of checking if i is even, just increment by 2.

String title1 = "Some title";
String title2 = "";
for (int i = 0; i < title1.length(); i += 2)
{
  title2 += title1.charAt(i);
}
Cruncher
  • 7,641
  • 1
  • 31
  • 65
Justin Ryder
  • 757
  • 9
  • 17
1

You algorithm is wrong, it seems what you need to do is to extract out every nth character from source string, for example:

String source = "Book";

End result should be "Bo"

The algorithm should be:

  1. Iterate through each character in the original string, use a stride as you need, in this case, a stride of 2 should do (so rather than increment by one, increment by the required stride)
  2. Take the character at that index and add it to your second string

The end result should be a string which holds every nth character.

Nim
  • 33,299
  • 2
  • 62
  • 101
0

I don't really understand what you are attempting, but I can tell you what you are doing. Your loop structure does the following:

  • when i = 0, it compares all characters in both strings (0 + n = n, so the inner loop goes from x - title1.length()).
  • when i = 1, compare all characters except the first one (for size x, 1 + n = x - 1 comparisons).
  • when i =2, compare x / 2 characters (for size x, 2 + n = x / 2)
  • when i = 3, compare x / 3 characters
  • ... and so on
  • System.out.print(title.charAt(0,1)) Shouldn't even compile. charAt(int) is the correct call. And if title length is greater than 0, this will always print a String with a single character -- the first one in title. And it will always be the same unless you reassign title to a different String.

Also this code will always throw an IndexOutOfBoundsException at title.charAt(i+x) when i = title.length() - 1 and x > 0.

MadConan
  • 3,749
  • 1
  • 16
  • 27