簡體   English   中英

用Java解析數字

[英]Parse a number with Java

我有一個字符串,我假設它是6位整數的零填充表示,例如:

"001234"

我想將其解析為Long對象,但是我想檢查它是否完全相同; 我想返回錯誤,如果它不是長度6,沒有填充零,等等。

在CI中將使用scanf的某些變體。 Java的方式是什么?

if(s.length() != 6) 
    throw new IllegalArgumentException("Input is not of length 6: " + s);
Pattern allDigits = Pattern.compile( "[0-9]+" );
if(!allDigits.matcher(s).matches()) 
    throw new IllegalArgumentException("Input is not numeric: " + s);
long val = Long.parseLong(s);

此代碼段可能會對您有所幫助。

   String test = "001234";
    long correctValue = 0;
    if (test.charAt(0) == '0' || test.length() != 6) {
        System.out.println("padded or incorrect length");

    } else {
               correctValue = Long.parseLong(test);             
    }
    System.out.println(correctValue);

嘗試此操作,技巧是Long.parseLong不接受尾隨空格或前導空格,但接受前導零,因此您只需要檢查length = 6

String input = "001234";
if (input.length() != 6) {
    throw new IllegalArgumentException(input);
}
long l = Long.parseLong(input);

實際上,它接受非零填充的“ 123456”,但我認為它符合您的要求。

AleksanderBlomskøld答案的一個變體:

Pattern allDigits = Pattern.compile("^\d{6}$");
if (!allDigits.matcher(s).matches()) 
    throw new IllegalArgumentException("Input is not numeric: " + s);
long val = Long.parseLong(s);

我會在regexp中進行String驗證。 如果有效,那么我將使用Long.parseLong

Long#parseLong將為您提供大部分幫助。 只需檢查是否有六位數字,並且結果是肯定的。 它不能用0以外的其他內容填充(因為解析將失敗)。

您是說要檢查長度嗎

if (text.length() != 6)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM