2013-05-20 171 views
0

对于我的程序,我想了解如何才能使用由用户输入的一串数字作为字符串;在空格处提取每个数字并将其解析为整数。从字符串中提取数字? Java

P.S我仍然是编程语言的新手,所以请以我能理解的方式解释,谢谢。

这是我迄今为止:

用户可以输入一个这样的序列号的:15 31 94 87 108 11 7 63 79

public int [] getNumbers(){ 

    Scanner reader = new Scanner (System.in); 

    String inputStr = reader.nextLine(); 

    int[] a = new int [10]; 
    String[] numb = new String [10]; 

    int space = inputStr.indexOf (" "); 
    int length = inputStr.length(); 

    for (int x = 0; x < numb.length; x++){ 

     numb [x] = inputStr.substring (0, space); 
     inputStr = inputStr.substring (space+1); 

     int num = Integer.parseInt (numb[x]); 
     System.out.println (num); 
     a[x] = num; 
    } 
    return a; 
} 

这在目前得到的第一数字,然后缩短字符串。我将如何去寻找下一个数字,并结束它,因为它出界了?谢谢。

回答

1

为此,您可以使用字符串的分割法:

String[] numbers = numb.split(" "); 
int[] a = new int [numbers.length]; 

for (int x = 0; x < numb.length; x++){ 
     a[x] = Integer.parseInt (numbers[x]);; 
} 
+0

感谢这么多。这是非常有帮助和可以理解的。 – Bao