So I was solving a problem on Techgig which goes like this : There I have to print the sequence of Fibonacci numbers till 10 places in array and the first two inputs were entered by the user.
My code goes like:
import java.io.*;
import java.util.*;
public class CandidateCode{
public static void main(String args1[]) throws Exception
{
Scanner sc=new Scanner(System.in);
int first=sc.nextInt();
int second=sc.nextInt();
int [] array=new int[10];
array[0]=first;
array[1]=second;
int i;
for(i=2;i<10;i++)
{
array[i]=first+second;
first=array[i-1];
second=array[i];
}
System.out.print("{"+array[0]);
for(i=1;i<10;i++)
{
System.out.print(","+array[i]);
}
System.out.print("}");
}
}
Now the sample input should go like 1 2 and output should be displayed as {1,2,3,5,8,13,21,34,55,89}
But they have used Test Case as 1~2 and the code when compiled gives InputMismatchException. Please provide me a method to remove this Exception
This code will resolve your problem.
import java.io.*;
import java.util.*;
public class CandidateCode{
public static void main(String args1[]) throws Exception
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
int first=Integer.parseInt(s.substring(0,s.indexOf("~")));
int second=Integer.parseInt(s.substring(s.indexOf("~")+1));
int [] array=new int[10];
array[0]=first;
array[1]=second;
int i;
for(i=2;i<10;i++)
{
array[i]=first+second;
first=array[i-1];
second=array[i];
}
System.out.print("{"+array[0]);
for(i=1;i<10;i++)
{
System.out.print(","+array[i]);
}
System.out.print("}");
}
}
Read a input string of format "Num1~Num2" and then extract the numbers from this string.