How to use hasNext() from the Scanner class?
Your code does not work because you create a new Scanner
object in every recursive call.
You should not use recursion for this anyways, do it iteratively instead.
Iterative version
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++;
}
}
}
Recursive version
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);
}
}
}
Change
if (s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
to:
while (s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
while
loops continues until the data exists, where as if
checks for only once.