Friday, July 31, 2009

How do i read a whole line as a String in Java?

I am trying to implement a code using java that will take in a whole line of inputs as one String. However, the number of inputs is unknown to me. I heard about Scanner and the scanner.nextLine() function but can't seem to implement it well and falls into an infinite loop. Anyone knows how to better implement it or work around it?

How do i read a whole line as a String in Java?
You can use BufferedReader class to read a entire line





The below is a sample program to read a entire line from console...





I have written username you can input a long line ... It will just read the entire line... and assign it to variable username








import java.io.*;





public class ReadString {





public static void main (String[] args) {





// prompt the user to enter their name


System.out.print("Enter your name: ");





// open up standard input


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));





String userName = null;





// read the username from the command-line; need to use try/catch with the


// readLine() method


try {


userName = br.readLine();


} catch (IOException ioe) {


System.out.println("IO error trying to read your name!");


System.exit(1);


}





System.out.println("Thanks for the name, " + userName);





}





} // end of ReadString class


No comments:

Post a Comment