Вопрос

Okay so I have to write a program that loops and continues to ask for a pair of numbers until the user enters -1 in which case the program terminates. The combination numbers will be written like this : " 10 2" Without the quotes. When I type it in I get an error any idea what is wrong with my code?

Here is my code:

import java.util.*;

public class Combinations
{
public static int combinations( int n, int p )
{ 
if ( p == 0 )      
    return 1;
else if ( n == p ) 
    return 1;
else              
    return ( combinations( n - 1, p - 1 ) + combinations( n - 1, p ) );
}

public static void main(String [] args)
{
    int a=0;
    int b=0;
    boolean end = false;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the combination numbers");
    while (end==false)
    {
        String line = scan.next();
        StringTokenizer str=new StringTokenizer(line, " ");
        String st = str.nextToken();
        a = Integer.parseInt(st);
        String st1 = str.nextToken();
        b = Integer.parseInt(st1);
        if(a==-1||b==-1)
        {
            end=true;
        }
        System.out.println(combinations(a,b));
    }
}
}
Это было полезно?

Решение 2

To get the full line use 'nextLine()' then tokenize it.

 String line = scan.nextLine();

Другие советы

Rather than using a StringTokenizer try

    String line = scan.nextLine();     // not next
    String str[] = line.split (" ");

    // check that str.length is 2
    String st = str[0];
    a = Integer.parseInt(st);
    String st1 = str[1];
    b = Integer.parseInt(st1);
    if(a==-1||b==-1)
    {
       break;
    }

use this ...

 String line = scan.nextLine();

instead of

 String line = scan.next();

because its not take value after space.......

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top