Reputation: 21
I am very new to Java and am in a Java intro class so I apologize if this question is offensively simple but I am wondering if it is possible to set a string equal to a method. I guess I already know the answer is no because Netbeans is throwing an error but I just don't know another way to program this question:
"Create a new string called passwd formed by concatenating every alternate non-space character in sentence ('sentence' is a string she had us create earlier in the assignment) 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. If the extracted alternate character is NOT a space, then add it to the new String. Do not include spaces."
With my limited Java knowledge all I can think to do is to set a new string equal to a "for" method, but apparently this isn't allowed. How would I do this?
Upvotes: 0
Views: 343
Reputation: 52185
To do what you are required, you will need to initialize the string to the sentence you want to process, the, loop for the length of the string using the .charAt() method and see if the Character is a space. To do this, you can use the Character.isWhiteSpace(). If the character is not a space, you can append it to a StringBuilder.
Upvotes: 2
Reputation: 36577
Even if it would be possible to somehow set a string equal to a "for" method (actually for
is a statement, not a method), what would the string contain then? "For"? That's certainly not what you want.
you need to a loop to go through the string sentence
So create a (for) loop.
retrieve characters from alternate index positions
See String.charAt().
If the extracted alternate character is NOT a space, then add it to the new String.
Learn how if
works. Character.isWhitespace() method might be useful.
Upvotes: 0
Reputation: 9134
In the assignment text there's everything you need to do. Even if you don't know Java, you can write down an informal algorthim:
Upvotes: 0
Reputation: 485
public String result() {
String result = "";
for (char c : log.toCharArray()) {
if (!" ".equals(c)) {
result += c;
}
}
return result;
}
Upvotes: -1
Reputation: 785156
You can use this code (assuming string is your original string):
StringBuffer passwd = new StringBuffer();
for (int i=0; i<string.length(); i+=2) {
if (string.charAt(i) != ' ')
passwd.append(string.charAt(i));
}
System.out.printf("passwd is: [%s]%n", passwd.toString());
Upvotes: 0