gpt4 book ai didi

java - 如何验证读取 1,000 到 999,999 范围内的数字输入的代码?

转载 作者:行者123 更新时间:2023-11-29 05:34:11 24 4
gpt4 key购买 nike

我让它取一个 1000 到 999999 范围内的数字,还允许使用逗号。我现在需要验证代码并提供适当的错误消息。

import java.util.Scanner;

public class ConsoleReader {

public static void main(String[] args) {
// TODO Auto-generated method stub

// get a connection to the keyboard
Scanner in = new Scanner(System.in);

// ask the user for input
System.out.print("Please enter an integer between 1,000 and 999,999: ");
// read user's input
String number = in.next();

// get the first part (no comma or thousands)
String firstPart = number.substring(0, number.length() - 4);
// get last three digits
String lastThreeDigits = number.substring(number.length() - 3);

// print the two without the comma
System.out.println(firstPart + lastThreeDigits);
}
{
if (in.hasNextInt())
{
String number = in.next();
}
else
{
System.out.println("Please try again.");
}
}
}

最佳答案

另一种方法是使用正则表达式验证其格式是否有效,替换逗号,将其解析为 int 并确保其在可接受的范围内。

String number = in.next(); 
if (number.matches("\\d{0,2}\\d\\,?\\d{3}") {
int intNumber = Integer.parseInt(number.replace(",", "");
if (number >= 1000 && number <= 999999) {
...
}
}

关于java - 如何验证读取 1,000 到 999,999 范围内的数字输入的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20072627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com