How to use something like the charAt for integers

六月ゝ 毕业季﹏ 提交于 2019-12-22 01:16:31

问题


I am trying to make a program that uses three digit numbers to identify items and I am trying to use something like the charAt method for integers or something. Im not too sure. Im a beginner and I apologize i just need help. Also I need a bit of help to use an if statement and relational operators. Im trying to do if the last digit in the number is less than 5 then it is {item} and if its greater than 5 then its this {item}. Something like that. Thank you so much in advance.

    String number;

    System.out.println("Enter three digit number: ");
    number = in.nextLine();

    switch (number.charAt(0))
    {
         //stuff
    }

    if (number > 5)
    {
      //it is this item
    {
    else
    {
      //it is the other item
    {

回答1:


There are at least two ways you can do it:

  1. String number = in.nextLine();
    char c = number.charAt(i); // i is the position of digit you want to retrieve
    int digit = c - '0';
    
  2. if you want to get ith digit from the end of an Integer, do:

    int digit = 0;
    while(i > 0) {
        digit = n%10;
        n /= 10;
        --i;
    }
    



回答2:


To check the last digit of a base-10 number, use the remainder operator:

if (number % 10 < 5) {
    // handle last digit is 0-4
} else {
    // handle last digit is 5-9
}


来源:https://stackoverflow.com/questions/32854399/how-to-use-something-like-the-charat-for-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!