You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java新手求助:读取指定数量人名并输出问候的代码问题

问题排查:Java Scanner读取姓名并输出问候功能实现

需求说明

  • 使用Scanner读取指定数量的陌生人姓名
  • 读取完成后在控制台输出Hello, 姓名
  • 若输入的陌生人数量为0,输出Looks empty
  • 若输入的数量为负数,输出Looks negative to me

参考输入输出示例

3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel

现有问题代码

Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();

while (num==0) {
  System.out.println("Oh, it looks like there is no one here");
  break;

} while (num<0) {
  System.out.println("Seriously? Why so negative?");
  break;
}

String[] numbers = new String[num];
for (int i=0; i< numbers.length;i++) {
  System.out.println("Hello, "+input.nextLine());
}

代码问题分析

  1. 语法错误的分支结构:连续使用两个while语句是非法语法,这里应该用if-else if分支判断——num的取值(正数、0、负数)是互斥的,完全不需要循环逻辑。
  2. nextInt()的换行符残留问题:input.nextInt()仅读取整数部分,输入时按下的换行符会留在输入缓冲区中,后续的input.nextLine()会先读取这个空换行符,导致第一个姓名被读取为空字符串。
  3. 输出文本不符合需求:现有代码的提示文本和需求不一致,比如需求要求输出Looks empty,代码中是Oh, it looks like there is no one here,需要修正。
  4. 负数数组长度的异常风险:当num为负数时,执行new String[num]会直接抛出NegativeArraySizeException,必须在确认num为正数后再创建数组。

修正后的代码

import java.util.Scanner;

public class GreetStrangers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        // 读取陌生人数量
        int num = input.nextInt();
        // 处理nextInt()后的换行符,避免后续读取空字符串
        input.nextLine();

        // 分支判断不同数量情况
        if (num < 0) {
            System.out.println("Looks negative to me");
        } else if (num == 0) {
            System.out.println("Looks empty");
        } else {
            // 读取指定数量的姓名并输出问候
            for (int i = 0; i < num; i++) {
                String name = input.nextLine();
                System.out.println("Hello, " + name);
            }
        }
        
        input.close();
    }
}

代码说明

  • 添加input.nextLine()消耗nextInt()后的换行符,解决空字符串读取问题。
  • 使用if-else if分支处理不同num取值,逻辑清晰且规避异常。
  • 仅当num为正数时才执行姓名读取和问候输出,避免创建负数长度数组。
  • 修正输出文本为需求指定内容。

内容的提问来源于stack exchange,提问作者Kris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 18:40:14