Java调用自定义方法获取cType、cSize返回nullnull问题求助
问题排查与修复方案
核心错误点
- 正则传参颠倒:
clotheType方法需要匹配FB/TS这类字母编码,调用时却传入了replaceAll("[^0-9]", "")提取的纯数字;clotheSize方法需要匹配02/03这类数字编码,调用时却传入了replaceAll("[^A-Z]", "")提取的纯字母,所有判断分支都无法命中。 - 字符串比较错误:Java中比较字符串内容必须使用
equals()方法,你使用的==是比较对象内存地址,字符串内容相同也会判断为不匹配。 - 数组遍历越界:循环条件
x <= clotheOrder.length会导致索引超出数组范围,触发数组越界异常,正确写法为x < clotheOrder.length。
修复后完整代码
public class Main { static String clotheOrder[] = {"FB02", null, null, null, "TS03", "GS04", null, "PA03"}; int clotheQuantity[] = {3, 0, 2, 0, 2, 2, 0, 0}; static String cType, cSize; public static void main(String[] args) { // 修正循环条件,避免数组越界 for (int x = 0; x < clotheOrder.length; x++) { if (clotheOrder[x] == null) { System.out.println("No order"); continue; } else { // 修正传参:类型传字母,尺码传数字 System.out.println(clotheType(clotheOrder[x].replaceAll("[^A-Z]", "")) + clotheSize(clotheOrder[x].replaceAll("[^0-9]", ""))); } } } static String clotheType(String type) { // 替换==为equals比较字符串内容 if (type.equals("FB") ) {cType = "Blouse .............";} else if (type.equals("TS") ) {cType = "T-Shirt ............";} else if (type.equals("GS") ) {cType = "Garterized Shorts ..";} else if (type.equals("PA") ) {cType = "Pants ..............";} else if (type.equals("PS") ) {cType = "Pencil Skirt .......";} else if (type.equals("CC") ) {cType = "Chinese Collar Polo ";} else if (type.equals("PW") ) {cType = "White Slacks .......";} else if (type.equals("RB") ) {cType = "Round Neck Blouse ..";} else if (type.equals("S") ) {cType = "Skirt ..............";} else if (type.equals("VN") ) {cType = "V-Neck Polo ........";} else {cType = "未知品类";} // 增加默认值避免返回null return cType; } static String clotheSize(String size) { // 替换==为equals比较字符串内容 if (size.equals("01")) {cSize = " (Extra-Small) ...";} else if (size.equals("02")) {cSize = " (Small) .........";} else if (size.equals("03")) {cSize = " (Medium) ........";} else if (size.equals("04")) {cSize = " (Large) .........";} else if (size.equals("05")) {cSize = " (X-Large) .......";} else if (size.equals("06")) {cSize = " (2X-Large) ......";} else if (size.equals("07")) {cSize = " (3X-Large) ......";} else if (size.equals("08")) {cSize = " (Add-ons) .......";} else {cSize = " (未知尺码)";} // 增加默认值避免返回null return cSize; } }
运行输出
Blouse ............. (Small) ......... No order No order No order T-Shirt ............ (Medium) ........ Garterized Shorts .. (Large) ......... No order Pants .............. (Medium) ........
内容的提问来源于stack exchange,提问作者Augustus Moran
相关产品推荐
相关产品推荐

