AndreiL
Welcome to AndreiL.
Enjoy your time.
Please log in.

Easy getline class for getting the input from user

Go down

Easy getline class for getting the input from user

Post by Lucaci Andrei on Wed Oct 10, 2012 8:21 pm

Hi. Recently I "ported" myself from C++ to Java, and tried to do some simple console applications. What surprised me was that the cout and cin methods from C++ in Java were much more complicate, in the sense of writing and implementing (cin in this case). So then I created a class which would help me get the input from the user. This method takes the whole stream from the input (meaning also the empty space character ' ') and returns it in a Java String. Also you can modify this so that it would return a Java StringBuffer class. Anyway, hope it helps those "porting" themselves from C++ to Java.
It's a public static method of the Cstdin Class, so you must call it by String line=Cstdin.getline();

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Cstdin {
public static String getline(){
try{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
str = in.readLine();
return (str);
}
catch (IOException e) {
return "";
}
}
}


Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Cstdin {
   public static String getline(){
      try{
          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
          String str = "";
          str = in.readLine();
          return (str);
      }
      catch (IOException e) {
         return "";
      }
   }
}
avatar
Lucaci Andrei
"Tata Lor"


Number of messages : 222
Points : 2266743
Reputation : 1007
Registration date : 2008-08-15
Age : 26
Location : Cluj-Napoca

View user profile http://www.andreil.wgz.ro

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum