2012-03-13 20 views
2

我已经从标准输入接受了一个输入。这个输入将是一个数字的一​​行。例如,对于变线的有效值为:在一条线上读取数字

1 2 3 4 5 6 7 8 9 10 

我知道有多少数字会有,我已经存储在这个变量N.我想这些数字存储大小的数组N.

String a=""; 
for(int i=0; i<line.length(); i++){ 
    if(line.charAt(i)!=' ') 
     a = a+ line.charAt(i); 
    else{ 
     numbers[x++]=Integer.parseInt(a); 
     a=""; 
    } 
} 
numbers[x]=Integer.parseInt(a); //to store the last number in the array 

有没有更有效的方法呢?

回答

2
String your_number_string; 
String[] numbers = your_number_string.split(" "); 
0

您可以使用String.split()分隔输入。

Check this.

String input = "1 2 3 4 5 6 7 8 9 10"; 
String[] splits = input.split(" "); 

for(String num : splits){  
    if (num != null && num.trim() != "") { 
     try { 
      numbers[x++] = Integer.parseInt(num); 
     } catch (NumberFormatException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
2

您可以使用String#split

String[] numbersAsString = line.split(" "); // one space, right? 
Listy<Integer> numbers = new ArrayList<String>(); // lists are better here 
for (String numberAsString:numbersAsString) { 
    try { 
    numbers.add(Integer.parseInt(numberAsString)); 
    } catch (NumberFormatException nfe) { 
    // input was not a number is not added to the list 
    } 
} 
0

在它的效率更高任何情况下使用StringBuilder#append()进行连接而不是调用多次a = a+

你的角色,