Results 1 to 6 of 6
Thread: Space for charAt()?
- 11-01-2010, 08:07 PM #1
Member
- Join Date
- Nov 2010
- Posts
- 3
- Rep Power
- 0
Space for charAt()?
greetings, im new to Java, and is programming in Dr.Java.
Im making a program that reads a string, and has a line shift everything the character "|" appears in the string. But I can't seem to get past the basic problem, og a simple space..
For eksample, if i type "A new day|its nice!", the program should print it as:
"A new day
its nice!"
instead, my program prints : "A", and thats it.. it stops when a space occurs..
The program is:
import java.util.Scanner;
class oppgave13 {
public static void main (String [] args) {
Scanner tastatur = new Scanner(System.in);
char tegn;
String setning = tastatur.next();
for (int i = 0; i < setning.length(); i++) {
tegn = setning.charAt(i);
if (tegn == '|') {
System.out.println(); }
if (tegn == ' ') {
System.out.print(" "); }
else {
System.out.print(tegn); }
}
}
}
Im pretty sure that this is the wrong one, but I can't seem to find a way to get the program to ignore the space and just keep on going with the other characters.. Any tips, oh great java gods?
Mr.T.
- 11-01-2010, 08:08 PM #2
Member
- Join Date
- Nov 2010
- Posts
- 3
- Rep Power
- 0
And by this, I mean this:
if (tegn == ' ') {
System.out.print(" "); }
;)
Mr. T
- 11-01-2010, 10:29 PM #3
why do you bother checking if its a space?
Why not just
regardless, please surround your blocks with [ code] tagsJava Code:if (tegn == '|') { System.out.println(); } else { System.out.print(tegn); }
it makes it easier to read :)
- 11-01-2010, 10:36 PM #4
In answer to your actual question, you need to look at the docs for the Scanner class.
Scanner (Java 2 Platform SE 5.0)
If you look at the method next(), it returns the next token. By default, tokens are separated by white space, which will include spaces.
You should probably use the nextline() method
- 11-02-2010, 06:01 PM #5
Member
- Join Date
- Nov 2010
- Posts
- 3
- Rep Power
- 0
Ah, sorry about that, new to the place ;) Will remember to do that next time ;)
As for the nextLine(), that did the trick. Thanks man ;) Read through a couple of the scanner class methods, and I see where I went wrong ;)
Again, thanks.
Mr. T
- 11-02-2010, 06:57 PM #6
Similar Threads
-
Help with charAt()
By HackerOfDoom in forum New To JavaReplies: 7Last Post: 03-21-2010, 05:27 PM -
using String.charAt() for semicolons
By porchrat in forum New To JavaReplies: 5Last Post: 01-11-2010, 01:40 PM -
SWT Canvas drawing realtive to image space not canvas space.
By bobbie in forum SWT / JFaceReplies: 0Last Post: 07-05-2009, 12:31 PM -
Palindrom - method charAt()
By user in forum New To JavaReplies: 10Last Post: 11-16-2008, 04:37 AM -
Help With Input.charAt(LastIndex);
By susan in forum AWT / SwingReplies: 1Last Post: 08-07-2007, 04:22 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks