如何同时打印int数组与String数组并按指定格式输出?
解决Java数组对应元素格式化打印问题
你的问题出在使用Arrays.toString()直接输出整个数组,导致三个数组的内容被整体拼接,无法实现元素一一对应的行式输出。要达到期望格式,需要遍历数组索引,逐个取出对应位置的元素拼接后打印。
修改后的完整代码
public class PracticeArray { public static int[] arr5 = {78, 59, 89}; public static String[] names = {"Jeno", "Jaemin", "Jaehyun"}; public static String[] result = {"Passed", "Failed", "Passed"}; public static void main(String[] args) { // 遍历数组索引,逐个输出对应元素组合 for (int i = 0; i < names.length; i++) { System.out.println(names[i] + " - " + arr5[i] + " - " + result[i]); } } }
关键修改说明
- 移除
Arrays.toString()的整体输出方式,改用for循环遍历数组索引,确保三个数组中同一位置的元素能对应组合 - 修正了
arr5中的58为59,匹配你期望的输出结果(若原代码是笔误) - 每次循环按
名字 - 分数 - 结果的格式拼接字符串并打印,实现逐行输出
输出结果
Jeno - 78 - Passed
Jaemin - 59 - Failed
Jaehyun - 89 - Passed
内容的提问来源于stack exchange,提问作者Boomchakamae2334
相关产品推荐
相关产品推荐

