如何将两个单词的共同字母大写?Java代码报错求助
代码错误排查与修正:将两个单词的共同字母转为大写
报错信息:
Main.java:22: error: cannot find symbol char character = words.charAt(i); ^ symbol: method charAt(int) location: variable words of type String[]
核心错误原因
words是字符串数组(String[]),而charAt(int)是String类的实例方法,仅能用于单个字符串对象,数组本身没有这个方法,直接调用words.charAt(i)会触发"找不到符号"的编译错误。
代码中其他逻辑问题
除上述报错外,代码还有多处逻辑偏差:
- 输入读取错误:用
nextInt()读取输入,但实际需要读取的是两个单词(字符串),nextInt()仅能读取整数,完全不符合需求。 - 数组初始化错误:用读取到的整数初始化
String数组,这和"输入两个单词"的需求完全不匹配,正确逻辑应是将输入的整行内容拆分为单词或字符。 - 内容比较错误:用
==比较words[i]和words[j],若为字符串对象,==比较的是引用地址而非内容;仅字符比较可直接用==。 - 输出错误:直接打印
words数组会输出内存地址,而非实际字符串内容。
修正后的代码
以下是实现需求的完整修正代码:
import java.util.Scanner; public class SameLetters { public static void main(String[] args) { Scanner sameletters = new Scanner(System.in); // 获取输入 System.out.println("Input two words: "); String input = sameletters.nextLine(); // 按空格拆分输入为两个单词 String[] words = input.split("\\s+"); // 验证输入是否为两个单词 if (words.length != 2) { System.out.println("MUST CONTAIN 2 WORDS"); sameletters.close(); return; } // 转为字符数组方便修改单个字符 char[] word1Chars = words[0].toCharArray(); char[] word2Chars = words[1].toCharArray(); // 遍历两个单词的字符,标记共同字母为大写 for (int i = 0; i < word1Chars.length; i++) { for (int j = 0; j < word2Chars.length; j++) { if (Character.toLowerCase(word1Chars[i]) == Character.toLowerCase(word2Chars[j])) { word1Chars[i] = Character.toUpperCase(word1Chars[i]); word2Chars[j] = Character.toUpperCase(word2Chars[j]); } } } // 转回字符串并输出 String result1 = new String(word1Chars); String result2 = new String(word2Chars); System.out.println(result1 + " " + result2); sameletters.close(); } }
修正说明
- 用
nextLine()读取整行输入,通过split("\\s+")按任意数量空格拆分为单词数组。 - 先验证输入是否为两个单词,不符合则直接提示退出。
- 将单词转为
char[]字符数组,便于修改单个字符的大小写。 - 遍历字符数组,忽略大小写比较字符,找到共同字母后统一转为大写。
- 将修改后的字符数组转回字符串,输出最终结果。
内容的提问来源于stack exchange,提问作者gusion
相关产品推荐
相关产品推荐

