You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何用简单方法提取输入数字的最后一位(无需while循环)

在Java中提取数字最后一位的简单实现

要提取输入数字的最后一位,取模运算% 10是最直接高效的方法,完全不需要while循环这类复杂操作,甚至比字符串转换更简洁。

核心实现思路

整数对10取模的结果就是它的最后一位数字。如果输入是负数,n % 10会返回负数结果,这时可以用Math.abs(n) % 10确保得到正数的最后一位。

修正后的代码示例

你提供的代码实际是在计算输入数字平方后的位数,和提取最后一位无关,以下是正确的实现:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入一个数字:");
        int n = in.nextInt();
        // 提取最后一位,兼容负数输入
        int lastDigit = Math.abs(n) % 10;
        System.out.println("数字的最后一位是:" + lastDigit);
    }
}

可选的字符串方法(不推荐,仅作参考)

如果一定要用字符串方式实现,也可以把数字转成字符串后取最后一个字符再转成整数,但性能不如取模运算:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入一个数字:");
        int n = in.nextInt();
        
        String numStr = String.valueOf(n);
        char lastChar = numStr.charAt(numStr.length() - 1);
        int lastDigit = Character.getNumericValue(lastChar);
        
        System.out.println("数字的最后一位是:" + lastDigit);
    }
}

内容的提问来源于stack exchange,提问作者Vilwin Varghese

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:55:12