簡體   English   中英

比較字符串整數問題

[英]Comparing String Integers Issue

我有一台讀取7個字符的字母數字代碼(由用戶輸入)的掃描儀。 String變量稱為“代碼”。

代碼的最后一個字符(第7個字符,第6個索引)必須為數字,其余的可以為數字或字母。

因此,我試圖抓住一個障礙,如果代碼中的最后一個字符不是數字(0到9),則該方法的其余部分將無法執行。

但是,我的代碼無法正常工作,即使我的代碼以0到9之間的整數結尾,if語句也將得到滿足,並打印出“代碼中的最后一個字符為非數字”。

示例代碼:45m4av7

CharacterAtEnd會按要求打印為字符串字符7。 但是我的程序仍然告訴我我的代碼非數字結束。 我知道我的數字值是字符串字符,但這不重要,對嗎? 我顯然也不能將實際的整數值與“ |”進行比較,這主要是為什么im使用String.valueOf並采用0-9字符串字符的原因。

String characterAtEnd = String.valueOf(code.charAt(code.length()-1));
System.out.println(characterAtEnd);

 if(!characterAtEnd.equals(String.valueOf(0|1|2|3|4|5|6|7|8|9))){
     System.out.println("INVALID CRC CODE: last character in code in non-numerical.");
     System.exit(0);

我無法一輩子,弄清楚為什么我的程序告訴我我的代碼(末尾有7)非數字結束。 它應該跳過if語句並繼續。 對?

String contains方法將在這里工作:

String digits = "0123456789";
digits.contains(characterAtEnd); // true if ends with digit, false otherwise

String.valueOf(0|1|2|3|4|5|6|7|8|9)實際上是"15" ,這當然不能等於最后一個字符。 這應該是有道理的,因為使用整數數學將0|1|2|3|4|5|6|7|8|9評估為15,然后將其轉換為String。

或者,嘗試以下操作:

String code = "45m4av7";
char characterAtEnd = code.charAt(code.length() - 1);
System.out.println(characterAtEnd);

if(characterAtEnd < '0' || characterAtEnd > '9'){
    System.out.println("INVALID CRC CODE: last character in code in non-numerical.");
    System.exit(0);
}

您在這里進行按位運算: if(!characterAtEnd.equals(String.valueOf(0|1|2|3|4|5|6|7|8|9)))

查看|之間的區別 ||

這部分代碼應使用正則表達式完成您的任務:

String code = "45m4av7";

if (!code.matches("^.+?\\d$")){
    System.out.println("INVALID CRC CODE");
}

另外,作為參考,有時在類似情況下也可以使用此方法:

/* returns true if someString actually ends with the specified suffix */
someString.endsWith(suffix);

由於.endswith(suffix)不使用正則表達式,因此,如果要遍歷所有可能的小寫字母值,則需要執行以下操作:

/* ASCII approach */
String s = "hello";
boolean endsInLetter = false;
for (int i = 97; i <= 122; i++) {
    if (s.endsWith(String.valueOf(Character.toChars(i)))) {
        endsInLetter = true;
    }
}
System.out.println(endsInLetter);

/* String approach */
String alphabet = "abcdefghijklmnopqrstuvwxyz";
boolean endsInLetter2 = false;
for (int i = 0; i < alphabet.length(); i++) {
    if (s.endsWith(String.valueOf(alphabet.charAt(i)))) {
        endsInLetter2 = true;
    }
}
System.out.println(endsInLetter2);

請注意,上述方法都不是一個好主意-它們笨拙且效率低下。

從ASCII方法開始,您甚至可以執行以下操作:

ASCII參考: http : //www.asciitable.com/

int i = (int)code.charAt(code.length() - 1);

/* Corresponding ASCII values to digits */
if(i <= 57 && i >= 48){
    System.out.println("Last char is a digit!");
}

如果需要單線,則堅持使用正則表達式,例如:

System.out.println((!code.matches("^.+?\\d$")? "Invalid CRC Code" : "Valid CRC Code"));

我希望這有幫助!

暫無
暫無

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

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