从字符串中提取数字? Java的 [英] Extract numbers from a string?! Java

查看:135
本文介绍了从字符串中提取数字? Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的程序,我正在尝试着想如何才能让用户输入一串数字作为字符串;提取每个数字的空格并将它们解析为整数。



PS我仍然是编程语言的新手,所以请以我能理解的方式解释,谢谢。 / p>

这是我到目前为止:

用户可以输入一系列数字,例如:15 31 94 87 108 11 7 63 79

  public int [] getNumbers(){

扫描器读取器=新的扫描仪(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 [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;
}

此时获取第一个数字,然后缩短字符串。我将如何去寻找下一个数字,并结束它,因为它出界了?谢谢。

解决方案

您可以使用字符串的拆分方法来完成此操作:

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

for(int x = 0; x a [x] = Integer.parseInt(numbers [x]);;
}


For my program I am trying to figure how I can go about taking a series of number as string entered by the user; extract each number at spaces and parse them into integers.

P.S I am still a newbie to the programming languages so please explain in a way that I can understand, thanks.

This is what I have so far:

A user may input a series of number like this: 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;
}

This at the moment get the first number, then shorten the string. How would I go about finding the next number and ending it with out having it going out of bound ? thank you.

解决方案

You can do this using string's split method:

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

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

这篇关于从字符串中提取数字? Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆