javajava.util.scannercharatbinomial-theorem

Finding character at particular location of String


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) ;
    }
}

The problem with creating a character variable using `.next().charAt(index)` is that the index number of the character (the single variable) is not known in the string (the length of the integer is not known), and also that the blank space has to be omitted which was entered by the user to separate the integer literal and the character literal. How can the character variable containing the single-digit variable be made ?

Solution

  • 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);