如何对整数使用charAt之类的东西 [英] How to use something like the charAt for integers
问题描述
我正在尝试制作一个使用三位数的数字来标识项目的程序,并且正在尝试使用诸如charAt方法之类的整数或其他内容.我不太确定.我是一个初学者,对不起,我只需要帮助.我还需要一些帮助来使用if语句和关系运算符.我试图做的是,如果数字中的最后一位数字小于5,则它是{item},如果数字大于5,则其是这个{item}.这样的事情.提前非常感谢您.
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
{
推荐答案
至少有两种方法可以实现:
There are at least two ways you can do it:
String number = in.nextLine();
char c = number.charAt(i); // i is the position of digit you want to retrieve
int digit = c - '0';
如果要从整数末尾获取第i个数字,请执行以下操作:
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;
}
这篇关于如何对整数使用charAt之类的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!