它涉及方法、字串、陣列和檔案。
這是我的代碼的一部分:當我嘗試呼叫 main 時出現空指標例外。請幫忙。
public static boolean isCapOrDigit(String[] arr){
for(int i=0;i<arr[i].length();i ){
if(Character.isUpperCase(arr[i].charAt(0)) && Character.isDigit(arr[i].charAt(0))){
return true;
}
}
return false;
}
uj5u.com熱心網友回復:
你的錯誤很微妙。
for (int i = 0; i < arr[i].length(); i ) {
顯然應該遍歷arr. 但它不一定會在最后停止......因為for回圈的停止條件不正確。
該運算式arr[i].length()為您提供第 i 個字串中的字符數,而不是陣列中的字串數。你需要這個:
for (int i = 0; i < arr.length; i ) {
可能還有第二個問題。上面的錯誤會給你一個ArrayIndexOutOfBoundsException. 但是如果你得到一個NullPointerException,這意味著你的方法是用一個包含null值的陣列呼叫的。在我看來,這確實是呼叫isCapOrDigit.
我懷疑整個方法是有缺陷的。這種方法應該測驗一個字串還是多個字串?
- 在前一種情況下,為什么要傳遞一個字串陣列?
- 在后一種情況下,如果某些字串符合條件而其他字串不符合條件,您應該回傳什么?
有元素,一個字串陣列的10個元素。我正在從檔案中讀取它。
好吧,看來您實際上并沒有準確讀取 10 個元素并將它們全部正確放入陣列中。一些陣列元素似乎是null.
最后,這是不正確的:
if (Character.isUpperCase(arr[i].charAt(0))
&& Character.isDigit(arr[i].charAt(0))) {
return true;
}
您正在測驗該字符是否同時是一個大寫字符和一個數字......。那是不可能的。數字不是大寫的。當然,您應該使用 OR;IE
if (Character.isUpperCase(arr[i].charAt(0))
|| Character.isDigit(arr[i].charAt(0))) {
return true;
}
uj5u.com熱心網友回復:
Stephen C的答案是正確的,應該被接受。我會建議對您的代碼進行一些改進。
對于每個回圈
您可以使用更簡單的代碼,即 for-each 語法。
for ( String s : arr ) {
…
}
代碼點,不是char
Java 中的char型別是遺留的,本質上是被破壞的。作為 16 位型別,char物理上無法表示大多數字符。
相反,使用代碼點整數。
for ( String s : arr ) {
OptionalInt codePoint = s.codePoints().findFirst() ; // If the string is empty, the `OptionalInt` will be empty.
if( codePoint.isPresent() ) {
boolean beginsUppercaseOrDigit = Character.isUpperCase( codePoint.get() ) || Chracter.isDigit( codePoint.get() ) ;
…
} else { // Else string is empty.
…
}
}
uj5u.com熱心網友回復:
使用正則運算式讓它變得如此簡單
你可以使用正則運算式:^(\\d|[A-Z]).*
這意味著你需要什么,匹配一個以數字\\d或|大寫字母開頭的字串,之后是[A-Z]可選的*任何內容.
import java.util.regex.*;
public class Main
{
public static void main(String[] args) {
System.out.println(Pattern.matches("^(\\d|[A-Z]).*", "5abc")); // true
System.out.println(Pattern.matches("^(\\d|[A-Z]).*", "Abc")); // true
System.out.println(Pattern.matches("^(\\d|[A-Z]).*", "5")); // true
System.out.println(Pattern.matches("^(\\d|[A-Z]).*", "abc5")); // false
System.out.println(Pattern.matches("^(\\d|[A-Z]).*", "aBc")); // false
System.out.println(Pattern.matches("^(\\d|[A-Z]).*", "a5c")); // false
}
}
您也可以使用此正則運算式^[1-9A-Z].*產生相同的結果
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475398.html
