We can do looping in java using while, do and for constructors. Here is a simple example that takes all the string characters entered by the user and displays it back when ‘\n’
is entered.
1: public class NewClass {
2: public static void main (String arg [])
3: {
4:
5: StringBuffer str= new StringBuffer();
6: char c;
7: System.out.print("Enter something");
8: try
9: {
10: while ((c=(char)System.in.read())!= '\n' )
11: {
12: str.append(c);
13:
14: }
15: }
16: catch (Exception e)
17: {System.out.println("I/O Error!");
18:
19: }
20: System.out.println("You entered: "+ str);
21: }
22: }
Here you can see that we are creating an object by using StringBuffer str= new StringBuffer()
The, we use while to append all characters to the string buffer till the user enters ‘\n’.
Here is the result:
run: Enter something I love GNU /n You entered: I love GNU /n BUILD SUCCESSFUL (total time: 6 seconds)




Join Techblog
Facebook Group
Read
Digg entries
Add techblog to
Google reader