long
format we simply return a statement that informs the user about this integer
overflow. The while-loop is in boldface.
This example shows the general format of a while-loop:public class FactorialTest { public static void main(String[] args) { DataInputStream in = new DataInputStream(new BufferedInputStream(System.in)); int n; try { n = Integer.parseInt(in.readLine()); if (n>20) { System.out.println(n + "! is too large to be calculated"); } else if (n<0) { System.out.println("singular value"); } else { System.out.println(n + "! = " + factorial(n)); } } catch (Exception e) { System.out.println(e); } } static long factorial(int n) { int i; long fac = 1; i = n; while (i>0) { fac = fac*i; i--; } return fac; } }
wherewhile (booleanExpression) { statements }
booleanExpression
is an expression that evaluates
to a boolean value (i.e. true
or false
)
and statements
are valid Java statements ended by semicolons. The repetition stops
when the condition is not fulfilled anymore and then Java continues
with commands following the last curly bracket.
This while-loop is convenient when implementing reading of data. In the example below we compute factorials of integers as long as we do not input a negative integer. When a negative integer is entered, the while-loop is left.do { statements } while (booleanExpression);
The two lines forming the skeleton of the post-checked while-loop are highlighted in the above application. When the application is run with redirecting standard input to a file, say with the commandimport java.io.*; public class FactorialsTest { public static void main(String[] args) { DataInputStream in = new DataInputStream(new BufferedInputStream(System.in)); int n = 0; do { try { n = Integer.parseInt(in.readLine()); if (n>20) { System.out.println(n + "! is too large to be calculated"); } else if (n>0) { System.out.println(n + "! = " + factorial(n)); } } catch (Exception e) { System.out.println("no integer entered; try again"); } } while (n>=0); System.out.println("end of loop"); } static long factorial (int n) { int i; long fac = 1; i = n; while (i>0) { fac = fac*i; i--; } return fac; } }
java FactorialsTest < inputfile
,
and with the inputfile
containing the lines
then you will see on your computer screen the following output lines:3 4 5 6 7 8 9 19 -1
3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 19! = 121645100408832000 end of loop