0

Say I have a terminal with 30 lines of height.

And say I have a loop that outputs 100 lines of output

for(int i=0; i<100; i++){
  System.out.println(i);
}

Is there a way I can output the first 30 lines, show text that says "Press enter to continue output...", show the next 30 lines when the user presses enter, etc?

I want to do this in the easiest manner possible. If I can use less somehow, that would be excellent.


Update

This needs to be implemented in the Java source code. The following is not a suitable solution:

java program | less'

Also, I will need to programmatically get the height of whatever terminal it is executed in.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
maček
  • 76,434
  • 37
  • 167
  • 198

3 Answers3

2

With less:

java program | less

or

for(int i=0; i<100; i++){
    if( i % 30 == 0) {
       System.out.println("Press enter to continue output...");
       System.in.read();
    }    
    System.out.println(i);   
}
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
2

Within Java:

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

for(int i=0; i<100; i++){
    if (i % 30 == 0) {
        System.out.println("Press enter to continue output...");
        r.readLine();
    }
    System.out.println(i);
}
Zarkonnen
  • 22,200
  • 14
  • 65
  • 81
1

Either pass tput cols to your java program as a command line arg or system property (java -DTermHeight=`tput cols`) or fetch it during runtime using Runtime.getRuntime().exec("tput cols")

Store that value in a variable height. Now

   height = (height==0?30:height);
    for(int i=1; i<=100; i++) {
        if (i % height== 0) {
            System.out.println("Press enter to continue output...");
            System.in.read();
        }
        System.out.println(i);
    }
Jagat
  • 1,392
  • 2
  • 15
  • 25
  • Marking this as accepted answer for providing means of getting terminal height using Java. Giving +1 to other answers. – maček Oct 13 '11 at 07:53
  • I am always getting '80' when running tput cols in Java, even though the same command in my terminal gives me a greater value. I am using JDK 1.7u51 – malaverdiere Apr 16 '14 at 13:49