Search code examples
javastringinputiochar

Character and String input in Java


I am new to Java and wrote a program for basic I/O operations of different data types. I want the program to input 1 a abcd and output them in in three different lines respectively. But when I input 1 a the program terminates and outputs 1 , a and an empty line in three different lines. I am not able to take a character input properly, which I think is the root of the problem. Can someone please guide me as to where I got it wrong ?

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

Solution

  • Refactor the code like below.

    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 
    
    

    output:

    1
    a
    abcd