I realized the issue was due to me creating a new scanner/reader object(the new scanner has a blank input), the issue still persists - how do I use the same input stream for both methods (or) how do I use the same scanner reader for both methods
Original question: how to pass on the main method input stream to called method
So I'm taking in formatted input which is like this from geek for geeks (this is important to my error)
1
4
1 2 3 4
And I am using scanner class to read the numbers into variables. This is my code
// code to print reverse of input string after reading the length of the string and no. of testcases
class Main {
public static void main (String[] args) {
int i,t,n;
String x,y;
Scanner scan = new Scanner(System.in);
try {
t=scan.nextInt();
scan.nextLine();
REV rv=new REV();
for (i=0;i<t;i ){
rv.reverse();
}
}catch (Exception e){
return;
}
}
}
class REV{
public void reverse(){
int i,a[],n;
Scanner scan = new Scanner(System.in);
try {
n=scan.nextInt();
scan.nextLine()
a= new int[n];
for (i=n-1;i>=0;i--){
a[i]=scan.nextInt();
}
System.out.println(a[i]);
}catch(Exception E){
return;
}
}
}
I get no output for this (java.util.NoSuchElementException if I don't use try and catch)
I am able to read the variables in the main method but my input stream becomes empty for the new method
I verified this by using nextLine()
both in the main()
method and reverse()
method as shown
public static void main (String[] args) {
int t,n;
String x,y,z;
t=scan.nextInt();
x=scan.nextLine();
n=scan.nextInt(); //to eat up the n input
y=scan.nextLine();
z=scan.nextLine();
System.out.println(x y);
....
}
output-
141 2 3 4
and
public void reverse(int n){
....
String k,j;
k = scan.nextLine(); //replacing n- to check what n=scanInt() reads
j= scan.nextLine();
System.out.println(x y);
....
}
Output is blank again (java.util.NoSuchElementException)
I think this means the input stream is empty for the reverse()
method.
So how do I pass on the main()
input to reverse()
Note: 1. if I don't use try{}
and catch{}
it gives me java.util.NoSuchElementException