Java程序报错:String无法转换为String[],求数组setter正确用法
解决"String cannot be converted to String[]"错误方案
错误原因
你的类中setName和setChangeAmount方法的参数是数组类型(String[]、double[]),但主程序调用时传入的是单个字符串(keyboard.next())和单个double值(keyboard.nextDouble()),类型不匹配导致编译错误。同时主程序存在语法错误:if(prompt = answer.equalsIgnoreCase("N"))是赋值操作,应改为判断相等的逻辑。
修复步骤
1. 初始化数组
在类的构造方法中初始化存储数据的数组,因要求至少10条数据,先设置数组长度为10:
public YourClassName() { name = new String[10]; changeAmount = new double[10]; }
(将YourClassName替换为你的实际类名)
2. 新增按索引设置的Setter方法
原Setter方法用于直接设置整个数组,现在新增按索引设置单个元素的方法,适配循环录入场景:
// 按索引设置单个姓名 public void setName(int index, String name) { if (index >= 0 && index < this.name.length) { this.name[index] = name; } else { throw new IndexOutOfBoundsException("索引超出数组范围"); } } // 按索引设置单个硬币面值 public void setChangeAmount(int index, double changeAmount) { if (index >= 0 && index < this.changeAmount.length) { this.changeAmount[index] = changeAmount; } else { throw new IndexOutOfBoundsException("索引超出数组范围"); } }
原数组Setter方法可保留,不影响新增方法的使用。
3. 修正主程序输入逻辑
调整调用方式,用循环索引作为参数传入新增的Setter方法,同时修复语法错误:
Scanner keyboard = new Scanner(System.in); System.out.println("Please enter at least 10 records to test the program"); for(int i = 0; i < 10; i++){ System.out.println("Please enter a name: "); changeC.setName(i, keyboard.next()); System.out.println("Please enter the coin value for the person: "); changeC.setChangeAmount(i, keyboard.nextDouble()); // 仅在未录入满10条时询问是否继续 if (i < 9) { System.out.println("Do you have more person to enter (Y/N): "); String answer = keyboard.next(); if(answer.equalsIgnoreCase("N")){ break; } } }
注:原逻辑允许用户提前结束录入,但可能导致数据不足10条,若需严格满足至少10条要求,可移除询问逻辑,或在用户选择提前结束时提示继续输入至满10条。
内容的提问来源于stack exchange,提问作者Jeremy Teong
相关产品推荐
相关产品推荐

