问题
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:
String number = in.nextLine(); char c = number.charAt(i); // i is the position of digit you want to retrieve int digit = c - '0';
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