[英]To check if an entered string is integer
在此程序中,我想檢查輸入的數字是否為10位整數移動電話,如果我輸入的值是0123456789,則可以正常工作,但是如果我輸入的則是5028608722,它將失敗。
包裝游戲;
import java.util.Scanner;
class Utility
{
static boolean numberOrNot(String input)
{
try
{
int i=Integer.parseInt(input);
System.out.println(i);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
}
public class CheckMobileNumber
{
public static void main(String[] args)
{
System.out.println("Enter your mobile number");
Scanner sc = new Scanner(System.in);
String input = sc.next();
if(Utility.numberOrNot(input) && (input.length() == 10))
{
System.out.println("Good!!! You have entered valid mobile number");
}
else
{
System.out.println("Sorry!!!! You have entered invalid mobile number. Try again...");
}
}
}
嘗試使用long
(長整數)數據類型而不是int
我認為您空間不足:2 ^ 32 = 4,294,967,296。
快速瀏覽一下原始數據類型 。
問題的直接原因是32位int類型不足以容納所有10位整數。
您最好為此使用正則表達式。 從技術上講,電話號碼不是整數,在這種情況下,它們就像整數一樣。 最好不要在軟件中將它們存儲為整數。 有一天,您可能需要處理電話號碼中的非數字字符。
Pattern phoneNumberPattern = Pattern.compile("\\d{10}");
if (phoneNumberPattern.matcher("5028608922").matches()) {
System.out.println("OK, phone number!");
} else {
System.out.println("Bad phone number!");
}
您的大價值(5028608722)無法放入帶符號的int中。 最大有符號整數為2 ^ 31-1 ==2147483647。正在使用的數字是5028608722,該數字太大。 為了使代碼正常工作,您需要更改為使用長類型。 例如:
import java.util.Scanner;
class Utility
{
static boolean numberOrNot(String input)
{
try
{
long i=Long.parseLong(input);
System.out.println(i);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
}
public class CheckMobileNumber
{
public static void main(String[] args)
{
System.out.println("Enter your mobile number");
Scanner sc = new Scanner(System.in);
String input = sc.next();
if(Utility.numberOrNot(input) && (input.length() == 10))
{
System.out.println("Good!!! You have entered valid mobile number");
}
else
{
System.out.println("Sorry!!!! You have entered invalid mobile number. Try again...");
}
}
}
使用Long.parseLong()
一種可選解決方案是使用正則表達式來匹配您的數字。 例如,這樣的正則表達式將為10位數字返回true,否則返回false:
"0123456789". match("[0-9]{10}")
將返回true。 任何非數字值或任何非10位數字的值都將返回false。
因此您的代碼可能如下所示:
import java.util.Scanner;
class Utility
{
static boolean numberOrNot(String input)
{
return input.matches("[0-9]{10}");
}
}
public class CheckMobileNumber
{
public static void main(String[] args)
{
System.out.println("Enter your mobile number");
Scanner sc = new Scanner(System.in);
String input = sc.next();
if(Utility.numberOrNot(input))
{
System.out.println("Good!!! You have entered valid mobile number");
}
else
{
System.out.println("Sorry!!!! You have entered invalid mobile number. Try again...");
}
}
}
除了正確的普通Java答案之外:我建議使用lib phonenumber作為電話號碼。 github.com/googlei18n/libphonenumber(如果您的興趣並非純粹是學術性的;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.