I’m trying to write the solution to this question: http://sharecode.io/section/problemset/problem/1088 but I’m getting a runtime error and Eclipse kepler and ideone.com compiling are different for me. I dont understand why.
And actually i want to ask why this code System.out.println("String #"+(i+1));
runs first in the for loop and `str = br.readLine();? doesnt work correctly in order?
import java.io.IOException; public class Main { public static void main(String args[]) throws IOException { java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in); java.io.BufferedReader br = new java.io.BufferedReader(isr, 16 * 1024); int testcase = br.read(); String str = ""; String[] strarray=null; for(int i=0;i<testcase;i++){ str = br.readLine(); strarray = str.split(""); for (int j = 1; j < strarray.length; j++) { if (strarray[j].equals("A")) strarray[j] = "B"; else if (strarray[j].equals("B")) strarray[j] = "C"; else if (strarray[j].equals("C")) strarray[j] = "D"; else if (strarray[j].equals("D")) strarray[j] = "E"; else if (strarray[j].equals("E")) strarray[j] = "F"; else if (strarray[j].equals("F")) strarray[j] = "G"; else if (strarray[j].equals("G")) strarray[j] = "H"; else if (strarray[j].equals("H")) strarray[j] = "I"; else if (strarray[j].equals("I")) strarray[j] = "J"; else if (strarray[j].equals("J")) strarray[j] = "K"; else if (strarray[j].equals("K")) strarray[j] = "L"; else if (strarray[j].equals("L")) strarray[j] = "M"; else if (strarray[j].equals("M")) strarray[j] = "N"; else if (strarray[j].equals("N")) strarray[j] = "O"; else if (strarray[j].equals("O")) strarray[j] = "P"; else if (strarray[j].equals("P")) strarray[j] = "Q"; else if (strarray[j].equals("Q")) strarray[j] = "R"; else if (strarray[j].equals("R")) strarray[j] = "S"; else if (strarray[j].equals("S")) strarray[j] = "T"; else if (strarray[j].equals("T")) strarray[j] = "U"; else if (strarray[j].equals("U")) strarray[j] = "V"; else if (strarray[j].equals("V")) strarray[j] = "W"; else if (strarray[j].equals("W")) strarray[j] = "X"; else if (strarray[j].equals("X")) strarray[j] = "Y"; else if (strarray[j].equals("Y")) strarray[j] = "Z"; else if (strarray[j].equals("Z")) strarray[j] = "A"; } System.out.println("String #"+(i+1)); for(int k =0 ; k<strarray.length;k++) System.out.print(strarray[k]); } } }
Answer
With
int testcase = br.read();
you read the first character from the input. And if your whole input is only one character, the entire line is already read, so that
str = br.readLine();
has nothing to to and the first output you see is: String #1
You can change reading the testcase number to:
int testcase = Integer.valueOf(br.readLine());
But you should handle NumberFormatException