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

Java中如何完整打印用户输入的整段字符串?

问题描述

我在Java代码里尝试打印用户输入的完整字符串,比如用户输入“golden retriever”时,当前代码只打印“golden's”,想获取并打印全部内容。试过用.nextLine()方法,但它直接跳过输入,打印后续的System.out.println(breed + "'s" + " are AWESOME!");这行。相关代码如下:

import java.util.Scanner;

public class Registration {
        static void PetWelcome() {
            Scanner scan = new Scanner(System.in);
            System.out.print("Pet's name: ");
            String name = scan.next().toUpperCase();
            System.out.println("Welcome, " + name + "!");
            System.out.println(name + ", we need more details about you.");
        
            System.out.print("What is your age in months?: ");
            int age = scan.nextInt();
            
            if(age < 3) {
                System.out.println("Too young to join the shelter.");
                return;
            } else {
                System.out.println("You meet the age requirement! Keep on going!");
            } 
            String petType;
            
            do {
                System.out.print("Are you a dog or a cat?: ");
                petType = scan.next().toUpperCase();
                break;
            } while(!petType.equals("cat") && (!petType.equals("dog")));
            
            // the issue
            System.out.print("What is your breed? ");
            String breed = scan.next().toUpperCase();
            System.out.println(breed + "'s" + " are AWESOME!");
    
            System.out.println("Thank you, " + name + " for taking the time to apply!");
        }
            
            static void OwnerInformation() {
            Scanner scan = new Scanner(System.in);
            System.out.println("Now we need the owner's information");
            System.out.print("What is your name?: ");
            String ownerName = scan.next();
    
            System.out.print("What is your phone number?: ");
            boolean flag;
            Scanner sc = new Scanner(System.in);
            do {
                String phonePattern = "\\d{3}-\\d{3}-\\d{4}";
                String input = sc.next();
                flag = input.matches(phonePattern);
                if (!flag) System.out.println("Enter phone number in ###-###-#### format.");
            } while (!flag);
            
            System.out.print("Enter your e-mail address: ");
            boolean flag2;
            Scanner sc1 = new Scanner(System.in);
            do {
                String emailPattern = "[a-zA-Z0-9]{3,20}@[a-zA-Z0-9]{3,15}[.][a-zA-Z]{1,5}";
                String input = sc1.next();
                flag2 = input.matches(emailPattern);
                if (!flag2) System.out.println("Invalid email.");
            } while (!flag2);
        }
}
问题原因与解决方法

核心问题

  • scan.next()只能读取到第一个空格,带空格的字符串会被截断。
  • 之前调用nextInt()、next()后,输入缓冲区会残留换行符,直接调用nextLine()会读取这个空行,导致跳过用户输入。

解决步骤

  1. 在调用nextLine()获取完整字符串前,先执行scan.nextLine()清空缓冲区的换行符。
  2. 替换scan.next()为scan.nextLine()来读取带空格的品种名。
  3. 复用同一个Scanner实例,避免创建多个实例导致的输入混乱。
修正后的完整代码
import java.util.Scanner;

public class Registration {
    // 全局复用一个Scanner实例
    private static final Scanner scan = new Scanner(System.in);

    static void PetWelcome() {
        System.out.print("Pet's name: ");
        String name = scan.next().toUpperCase();
        System.out.println("Welcome, " + name + "!");
        System.out.println(name + ", we need more details about you.");

        System.out.print("What is your age in months?: ");
        int age = scan.nextInt();
        
        if(age < 3) {
            System.out.println("Too young to join the shelter.");
            return;
        } else {
            System.out.println("You meet the age requirement! Keep on going!");
        } 
        String petType;
        
        do {
            System.out.print("Are you a dog or a cat?: ");
            petType = scan.next().toUpperCase();
            // 修正循环条件,匹配大写的DOG/CAT
        } while(!petType.equals("DOG") && !petType.equals("CAT"));
        
        // 清空之前操作残留的换行符
        scan.nextLine();
        // 读取完整的带空格品种名
        System.out.print("What is your breed? ");
        String breed = scan.nextLine().toUpperCase();
        System.out.println(breed + "'s are AWESOME!");

        System.out.println("Thank you, " + name + " for taking the time to apply!");
    }
        
    static void OwnerInformation() {
        System.out.println("Now we need the owner's information");
        System.out.print("What is your name?: ");
        String ownerName = scan.next();

        System.out.print("What is your phone number?: ");
        boolean flag;
        do {
            String phonePattern = "\\d{3}-\\d{3}-\\d{4}";
            String input = scan.next();
            flag = input.matches(phonePattern);
            if (!flag) System.out.println("Enter phone number in ###-###-#### format.");
        } while (!flag);
        
        System.out.print("Enter your e-mail address: ");
        boolean flag2;
        do {
            String emailPattern = "[a-zA-Z0-9]{3,20}@[a-zA-Z0-9]{3,15}[.][a-zA-Z]{1,5}";
            String input = scan.next();
            flag2 = input.matches(emailPattern);
            if (!flag2) System.out.println("Invalid email.");
        } while (!flag2);
    }

    // 主方法用于测试
    public static void main(String[] args) {
        PetWelcome();
        OwnerInformation();
        scan.close();
    }
}

关键修改说明

  • 全局共享一个Scanner,避免多实例导致的输入异常。
  • 添加scan.nextLine()清除缓冲区换行符,确保nextLine()能正确读取用户输入的完整字符串。
  • 修正宠物类型判断的循环条件,之前因大小写不匹配导致逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:28:13