Java 中的字符和字符串输入

Character and String input in Java

我是 Java 的新手,并为不同数据类型的基本 I/O 操作编写了一个程序。我希望程序输入 1 a abcd 并分别在三个不同的行中输出它们。但是当我输入 1 a 程序终止并输出 1a 和三个不同行的空行。我无法正确输入字符,我认为这是问题的根源。 有人可以指导我哪里错了吗?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        char nextChar() {
            char c = ' ';
            try {
                c = (char)br.read();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return c;
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    public static void main(String[] args) {
        FastReader in = new FastReader();
        PrintWriter out = new PrintWriter(System.out);
       int n = in.nextInt();
        char c = in.nextChar();
        String s = in.nextLine();
        out.println(n);
        out.println(c);
        out.println(s);
        out.close();
    }
}

重构如下代码。

char c = in.nextChar();//Keep this line as same
in.nextLine();//(only add this line after the above line)Place this line otherwise your String abcd can't insert 

输出:

1
a
abcd

你的意思是关注:

input: 1 a abcd
out:
1
a
abcd

您引用了这段代码:

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String inputLine = bufferedReader.readLine();
        if (inputLine!=null && inputLine.length()>0) {
            String[] splitInputLine = inputLine.split("\ ");
            for (String outLine : splitInputLine) {
                System.out.println(outLine);
            }
        }
        bufferedReader.close();
    }