来自用户的整数的组合

时间:2014-04-30 05:49:57

标签: java combinations

好吧所以我必须编写一个程序循环并继续询问一对数字,直到用户输入-1,在这种情况下程序终止。组合编号将如下所示:" 10 2" 没有引号。当我输入它时,我得到一个错误,知道我的代码有什么问题吗?

这是我的代码:

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

3 个答案:

答案 0 :(得分:3)

而不是使用StringTokenizer尝试

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

答案 1 :(得分:2)

要全线使用' nextLine()'然后将其标记化。

 String line = scan.nextLine();

答案 2 :(得分:2)

使用此...

 String line = scan.nextLine();

而不是

 String line = scan.next();

因为它没有在空间后取值.......