开发者

Converting a character to an integer if the character is already a number in java

开发者 https://www.devze.com 2023-02-14 09:36 出处:网络
I\'m trying to read a string\'s character to get the numeric value. String cardNumber = in.next(); int currentIndex = cardNumber.length() - 1;

I'm trying to read a string's character to get the numeric value. String cardNumber = in.next();

  int currentIndex = cardNumber.length() - 1;
  while (currentIndex >= 0)
    {

   开发者_运维知识库   int smallValue;
      smallValue = Character.getNumericValue(currentIndex);

when smallValue runs, its not giving me the number. just a -1


You should be using Character.digit(), but you are calling it with the array index instead of the element value at that index.


You are passing currentIndex to Character.getNumericValue. I think you actually want to pass one of the characters of cardNumber.


I think this is what you want:

int currentIndex = cardNumber.length() - 1;
while (currentIndex >= 0)
    {
         int smallValue = Character.digit(cardNumber[i], 10);
    }


Assuming cardNumber is a String, I believe this is what you want:

int smallValue = Character.digit(cardNumber.charAt(currentIndex), 10);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号