java键盘循环录入字符串,输入end后就停止循环录入,最后如何将键盘录入的所有字符串打印出来

谢谢,在线等
2025-04-03 14:05:06
推荐回答(1个)
回答1:


//filename: A.java
public class A {
    /**
     * 调用方法获取输入的字符串
     */
    public static String getLines(String end) 
            throws Exception {
        StringBuffer sb = new StringBuffer();
        Scanner reader = new Scanner(System.in);
        String line;
        
        while (reader.hasNext()) {
            line = reader.nextLine();
            sb.append(line);
            if (line.endsWith(end)) {
                break;
            }
        }
    
        return sb.toString();
    }
    //以下是调用代码
    public static void main(String[] args) {
        try {
            String lines = getLines("end");
            System.out.println(lines);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}