有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    重构代码,如下所示

    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
    
  2. # 2 楼答案

    你的意思是像下面这样:

    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();
        }