【问题标题】:How do I select the first, second, or third digit from a String containing three digits? [closed]如何从包含三位数字的字符串中选择第一位、第二位或第三位数字? [关闭]
【发布时间】:2016-05-02 03:33:21
【问题描述】:

所以说代码是这样的..

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() 但我找不到其他任何东西... 提前谢谢各位!还在学习!

【问题讨论】:

  • 您尝试了 charAt() 并且...有什么问题?
  • Integer.parseInt(nbr.substring(0,1))...
  • 我很困惑问题是什么...... charAt() 给你你想要的字符。您将其转换为 int。问题解决了。

标签: java string char int


【解决方案1】:

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

int a = Character.getNumericValue(nbr.charAt(0));

【讨论】:

  • 它说:无法在原始类型 int 上调用 charAt(int)... 有什么帮助吗?
  • @Austin Load nbr 应该是一个字符串,通过String nbr = input.nextLine()检索
【解决方案2】:

你可以试试这个。

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

【讨论】:

  • 你给我的第一个选项有效!非常感谢!我不确定为什么 charAt() 事先没有工作......也许没有正确使用它,但问题现在已经解决了!
  • charAt() 返回字符的 unicode 代码,而不是字符的数字表示。所以“258”.charAt(0) 的 char '2' 的 unicode 代码是 50,而不是 2。希望这会有所帮助。
猜你喜欢
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2017-02-01
  • 2019-12-29
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多