I tried reading the space-separated inputs 5 3
for my code using Scanner
class which works fine using nextInt()
method. When I switched to BufferReader
class for faster I/O, using readLine()
does not accept the space-separated inputs as separate integers.
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
try{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
int t= Integer.valueOf(br.readLine());
while(t-->0){
int mel=Integer.valueOf(br.readLine());
int ban=Integer.valueOf(br.readLine());
System.out.println(cho(mel,ban));
}
}catch(Exception e){
return;
}
}
public static int cho(int m,int b)
{
if(m==0 || b==0 || (m==b))
{
return (m b);
}
else
{
return m>b? cho((m-=b),b): cho(m,(b-=m));
}
}
}
**Inputs** 2 5 3 10 10
**Expected Outputs** 2 20
`My Outputs 2 5 3
...Program finished with exit code 0 Press ENTER to exit console. `
CodePudding user response:
Integer.valueOf(br.readLine());
reads the whole line and parses it to integer value so it expects only single integer value in the string. If you want to parse multiple integers from a line separated by space you first need to split it (or use do a regex search). For example br.readLine().split(" ");
and then iterate over the array of strings and parse them as integers