如何从包含三位数的字符串中选择第一个,第二个或第三个数字?

时间:2016-01-25 17:59:49

标签: java string char int

所以说代码是这样的..

String nbr = input.nextLine();    // For example say it's 258
int a;    // I want this to be the first digit of nbr
int b;    // This the second
int c;    // And this the third

我试过charAt(),我找不到任何其他东西...... 先谢谢你们!还在学习!

2 个答案:

答案 0 :(得分:1)

你可以试试这个。

String nbr = input.nextLine();    
int a=nbr.charAt(0)-'0';    
int b=nbr.charAt(1)-'0';    
int c=nbr.charAt(2)-'0';    

此外,您可以使用子字符串并使用Integer.parseInt

解析结果
int a=Integer.parseInt(nbr.substring(0,1)); //Contains the leftmost digit

答案 1 :(得分:0)

我猜测问题是charAt()返回一个char。你只需要转换它,例如:

mavenRepo 'http://central.maven.org/maven2'