I have adapted a solution that seemed fine to me that was posted several years ago. When I tested it in an IDE I noticed that the PrintWriter caused the program to store the outputs until the end command "42" was reached. I then changed writer.println(s) to System.out.println(s) and indeed now the input was also returned as output immediately after pressing Enter. However, I still got a runtime error. Then, I changed int N = nextInt(); to String s = nextToken();. Still a runtime error. However, I now have found out that for some reason I cannot input strings, even though the nextToken() method returns tokenizer.nextToken().
Can anybody explain why the code below results in an NZEC runtime error? Keep in mind that the outputs are displayed after every input (which is commonly not the case for the NZEC runtime errors with this problem). I also don't know why my outputs are supposedly displayed "properly", as I don't see the difference between writer.println() and System.out.println(). Then I also wonder why I get an error whenever I input a string that is strictly not also a numeric value.
Any help would be appreciated!
/*
*
* Date: 01-10-2014
* Problem Statement link: http://www.spoj.com/problems/TEST/
* Main site of P.S.: http://www.spoj.com/
*
* Task name: TEST
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
// import java.math.*;
import java.util.*;
public class Main
{
private void solve() throws IOException
{
for (; ; )
{
String s = nextToken();
if (Integer.parseInt(s) == 42)
break;
System.out.println(s);
}
}
public static void main(String arg[])
{
new Main().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run()
{
try
{
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
// System.exit(0); // MUST INCLUDE THIS; VITAL FOR SUBMISSION TO SPOJ
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException
{
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException
{
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException
{
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}