As a part of a Binomial expansion program, I created a Scanner class (sc
) on an entered number + variable, and another (scan
)on the first term (a in (a+b)n)
Here's my program till now :
import java.util.* ;
public class binomial_expansion
{
public static long factorial(long x)
{
long xf = x ;
for(long i = 1; i<=x ; i++)
{
xf*=i ;
}
return xf ;
}
public static double C(long n, long r)
{
double c = factorial(n)/(factorial(n-r)*factorial(r)) ;
return c ;
}
public static void main()
{
Scanner sc = new Scanner(System.in) ;
boolean error = false ;
String a = "" ;
do {
if(error)
{
System.out.println("Error; Please try again") ;
error = false ;
}
System.out.println("Enter a (separate single variable with space) : ") ;
a = sc.nextLine() ;
if(a=="") error = true ;
} while(error) ;
sc.close() ;
Scanner scan = new Scanner(a) ;
long x = scan.nextLong() ;
long x1 = scan.next().charAt(0) ;
}
}
You'll only need one Scanner
to get the input, which you do with a = sc.nextLine()
.
From there, find the index of the space, and use the String.substring
method to derive each value.
Scanner sc = new Scanner(System.in) ;
boolean error = false ;
String a = "" ;
do {
if(error)
{
System.out.println("Error; Please try again") ;
error = false ;
}
System.out.println("Enter a (separate single variable with space) : ") ;
a = sc.nextLine() ;
} while(error) ;
sc.close() ;
int indexOf = a.indexOf(' ');
long number = Long.parseLong(a.substring(0, indexOf));
char variable = a.charAt(indexOf + 1);