problem of String

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
Morning
Experienced poster
Posts: 134
Joined: Fri Aug 01, 2003 2:18 pm
Location: Shanghai China

problem of String

Post by Morning »

I use the java input function that provided from acm.uva.es
[java]
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";

try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}

if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String[] args)
{
String input;
input = Main.ReadLn (255);
{
System.out.println(input+"Hello World!");
}
}
}
[/java]
if i input "abcdefghijklmn",
i suppose that abcdefghijklmnHello World will be print,but Hello World!mn is output.why??????????????
"Learning without thought is useless;thought without learning is dangerous."
"Hold what you really know and tell what you do not know -this will lead to knowledge."-Confucius
Spike
New poster
Posts: 29
Joined: Mon Mar 18, 2002 2:00 am
Location: Washington State
Contact:

Post by Spike »

Think of it as like printing on a typewriter, there are two different things that you have to do for a line to be printed. You hit enter and it takes you down to the next line. Then you push the roll back over to the other side. These commands are called line feed and carriadge return.

you're escaping after you hit the \n character, but not including it in the output string. What your input string actually looks like to the java program is something like:

"abcdefghijklmn\r\n"

You're picking up the \r but not the \n, so it's writing to the screen, then setting the pointer back to the start of the line, but not moving down a line. Putting your lin[lg++] += car; statement before the if statement should give you the following:

abcdefghijklmnop
Hello World

I also wrote some of my own methods that I feel work better then the ones that UVA has provided which you can find on the boards here...

http://online-judge.uva.es/board/viewto ... d0495f2822

Hope this helps.
Post Reply

Return to “Java”