How to take input as String with spaces in java using scanner

前端 未结 7 1785
春和景丽
春和景丽 2021-02-02 04:29

I need to read spaces (present before string and after String) given as input using Scanner Note : if there is no spaces given in input it should not add space in output

7条回答
  •  迷失自我
    2021-02-02 04:46

    I use this function below, to read from all user input format, text inclusive spaces, then parse to specific datatype after.

    package practice;
    import java.io.*;
    
    public class readInputSample{
       public static void main(String[] args) {
            String strVal = getInput("Enter string value: "); // Direct as string
            Integer intVal = Integer.parseInt(getInput("Enter integer value: "));
            Double dblVal = Double.parseDouble(getInput("Enter double value: "));
            Float fltVal = Float.parseFloat(getInput("Enter float value: "));
    
            System.out.println("String value: " + strVal);
            System.out.println("Integer value: " + intVal);
            System.out.println("Double value: " + dblVal);
            System.out.println("Float value: " + fltVal);
       }
    
       // Special Function to read all user input
       private static String getInput(String prompt){
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    
          System.out.print(prompt);
          System.out.flush();
    
          try{
              return stdin.readLine();
          } catch (Exception e){
            return "Error: " + e.getMessage();
          }
        }
    }
    

提交回复
热议问题