您的代码不起作用,因为您Scanner
在每次递归调用中都创建了一个新对象.不管怎么说,你不应该使用递归,而是迭代地进行.
迭代版
public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); int count = 1; while(s.hasNext()) { String ns = s.nextLine(); System.out.println(count + " " + ns); count++; } } }
递归版
public class Solution { private Scanner s; public static void main(String[] args) { s = new Scanner(System.in); // initialize only once check(1); } public static void check(int count) { if(s.hasNext()) { String ns = s.nextLine(); System.out.println(count + " " + ns); check(count + 1); } } }