0

If I input whitespace from console , console print this as a string . but, if I do it directly, it works correctly . why ? How can I print whitespace as a whitespace from console input?

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.print("Input Whitespace :");
    String ss = sc.nextLine();//input whitespace from console 
    String st ="\n \t";//input whitespace directly 
    System.out.println("print whitespace direcly :"+st+"print whitespace from console : "+ss);

}

input : Input Whitespace :\n \t

output : print whitespace direcly : print whitespace from console : \n \t

1 Answers1

1

Yes, now it will work :

    ss=ss.replace("\n", "\\n");
    ss=ss.replace("\t", "\\t");
    ss=ss.replace("\f", "\\f");
    ss=ss.replace("\r", "\\r");
    ss=ss.replace("\\n", "\n");
    ss=ss.replace("\\t", "\t");
    ss=ss.replace("\\f", "\f");
    ss=ss.replace("\\r", "\r");
  • Can you explain what the purpose of the first four lines is? `ss` doesn't contain these whitespaces, so you don't need to replace them. – Tom Apr 27 '16 at 12:20
  • As I want to use \n,\t,\f,\r as a whitespace . So, I have to do this. Else, whitespace(new line , tab ) is not printing only \n \t \r \f are printing. – Farhan Rahman Arnob Apr 27 '16 at 18:43
  • @tom . I think you can't understand my problem. – Farhan Rahman Arnob Apr 27 '16 at 18:45
  • *"I think you can't understand my problem"* No, you don't understand what you're doing there. The first four lines are useless when you want to convert manually entered `\n` (or the whitespace representations) strings. You only need the latter four `replace` calls. – Tom Apr 27 '16 at 19:36