Java购物清单统计代码运行报数组下标越界,无法定位错误原因
数组下标越界问题原因及修复方案
错误根源
1. 数组长度与循环条件不匹配
你统计的count是输入内容中逗号的数量:
- 例如输入
mango$12,tomato$14时,逗号数量为1,count=1 - 用逗号分割得到的商品数组
temp长度为count+1=2 - 你初始化
price数组时长度设为count=1,同时循环条件写为i<=count,当i=1时访问price[1]就超出了数组的下标范围(数组下标从0开始,长度为1的数组仅能访问price[0]),直接触发越界异常。
2. 输入读取方法存在隐患
Scanner.next()默认按空格分割读取内容,如果用户输入的商品名包含空格,会导致读取内容不全,后续处理也会触发异常。
修复后可运行代码
import java.util.Scanner; public class Question1 { public static void main(String[] args){ System.out.println(" Welcome to Shopping"); System.out.println("Please enter your shopping (item$price and seperate by comma): "); Scanner scanner = new Scanner(System.in); // 读取整行输入,避免空格截断内容 String list = scanner.nextLine(); System.out.println("Here is the list of items:"); int totalPrice = 0; // 直接按逗号分割得到所有商品项 String[] itemList = list.split(","); // 价格数组长度和商品数组长度保持一致 int[] priceArr = new int[itemList.length]; for(int i = 0; i < itemList.length; i++){ String current = itemList[i]; int dollarPos = current.indexOf("$"); // 提取商品名 String itemName = current.substring(0, dollarPos); // 提取价格并转为整数 priceArr[i] = Integer.parseInt(current.substring(dollarPos + 1)); totalPrice += priceArr[i]; // 输出带序号的商品信息 System.out.println("No." + (i + 1) + " " + itemName); } System.out.println("The total price is: $" + totalPrice + "."); System.out.println("Thank you for using this program!!"); scanner.close(); } }
注意事项
- 输入时请使用半角符号
$分隔商品名和价格,不要使用全角$,否则会导致找不到$符号触发异常 - 不要输入连续逗号、首尾带逗号的内容,避免出现空商品项触发处理异常
内容的提问来源于stack exchange,提问作者Tmadwh
相关产品推荐
相关产品推荐

