不使用try/catch检查用户输入的整数/非整数-Java
创始人
2024-12-29 12:00:23
0

可以使用正则表达式来检查输入是否是整数或非整数。下面是一个示例代码:

import java.util.Scanner; import java.util.regex.Pattern;

public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入一个整数或非整数:"); String userInput = input.nextLine();

    Pattern integerPattern = Pattern.compile("^-?\\d+$"); //整数的正则表达式
    Pattern nonIntegerPattern = Pattern.compile("^-?\\d+\\.\\d+$"); //非整数的正则表达式

    if (integerPattern.matcher(userInput).matches()) { //匹配整数的正则表达式
        int userInt = Integer.parseInt(userInput);
        System.out.println(userInt);
    } else if (nonIntegerPattern.matcher(userInput).matches()) { //匹配非整数的正则表达式
        double userDouble = Double.parseDouble(userInput);
        System.out.println(userDouble);
    } else {
        System.out.println("输入不是整数或非整数。");
    }
}

}

相关内容

热门资讯

透视开挂"hhpko... 透视开挂"hhpkoer辅助器视频"切实是真的辅助攻略(哔哩哔哩)该软件可以轻松地帮助玩家将hhpk...
透视详细"wepok... 透视详细"wepoker究竟有没有透视"确实是有辅助app(哔哩哔哩)1、wepoker究竟有没有透...
透视解谜"we-po... 透视解谜"we-poker有人玩吗"确实是有辅助神器(哔哩哔哩)1、we-poker有人玩吗脚本辅助...
透视揭幕"红龙pok... 透视揭幕"红龙poker辅助平台"好像有辅助挂(哔哩哔哩)1、红龙poker辅助平台免费脚本咨询教程...
透视透视"wpk模拟... 透视透视"wpk模拟器多开"其实存在有辅助软件(哔哩哔哩)1、任何wpk模拟器多开透视是真的假的的玩...
透视总结"德州私人局... 透视总结"德州私人局脚本"本来有辅助神器(哔哩哔哩)1、很好的工具软件,可以解锁游戏的德州私人局脚本...
透视教你"红龙pok... 透视教你"红龙poker有辅助吗"真是有辅助技巧(哔哩哔哩)1、红龙poker有辅助吗免费脚本咨询教...
透视解密"poker... 透视解密"pokermaster修改器"真是有辅助工具(哔哩哔哩)1、首先打开pokermaster...
透视解密"德普软件&... 透视解密"德普软件"切实真的有辅助软件(哔哩哔哩)1、很好的工具软件,可以解锁游戏的德普软件辅助插件...
透视揭幕"wepok... 透视揭幕"wepoker数据分析"本来是真的辅助技巧(哔哩哔哩)1、首先打开wepoker数据分析辅...