import java.io.*; // Package with the Input/Output methods
// on File objects
import java.util.Scanner; // Class to read in data types
public class MyProg
{
public static void main( String[] args ) throws IOException
{
File inpFile = new File ( "PathNameOfInputFile" );
Scanner inp = new Scanner ( inpFile );
// Now you can read data in with:
// inp.nextDouble();
// inp.nextInt();
// ...
//
// You can also TEST if there is data in input with:
// inp.hasNextDouble();
// inp.hasNextInt();
// ...
}
}
|
|
Open the data file
Create an array a of a certain size (any size, we can change it)
while ( there is more data in input file )
{
x = read next input value
if ( array a is full ) then
increase the size of array a
store x into the next element of array a
}
|
|
Open the input file inp
double[] a = new double[1]; // Start with an array
// of 1 element
n = 0; // n counts the number of items in array
// (to detect if array is full or not)
while ( inp.hasNextDouble() )
{
x = inp.nextDouble(); // Read in next number
/* ------------------------------
Check if array has space left
------------------------------ */
if ( n == a.length )
{
/* ==========================================
Array is full... increase its size first
========================================== */
double[] h; // help variable to make a bigger array
h = new double[ 2*a.length ]; // make aray twice as big
for ( int i = 0; i < a.length; i++ )
h[i] = a[i]; // copy old values
a = h; // make "a" point to new array
}
/* ==========================================
Here, the array will surely have space
========================================== */
a[n] = x; // Put number read in a[n]
n++; // Go to next array position
}
|
import java.io.*;
import java.util.Scanner;
public class ArrayDoubling
{
public static void main(String[] args) throws IOException
{
File inpFile = new File( "ArrayDoubling.inp" );
Scanner inp = new Scanner ( inpFile );
double[] a = new double[1];
double x;
int n; // Number of items
n = 0;
while ( inp.hasNextDouble() )
{
x = inp.nextDouble();
/* ---------------------------------------
Check if array has space to store x
--------------------------------------- */
if ( n == a.length )
{
/* ==========================================
The array double algorithm
========================================== */
double[] h; // help variable to make a bigger array
h = new double[ 2*a.length ]; // make aray twice as big
for ( int i = 0; i < a.length; i++ )
h[i] = a[i]; // copy old values
a = h; // make "a" point to new array
}
/* ==========================================
Here, the array will surely have space
========================================== */
a[n] = x; // Put number read in a[n]
n++; // Go to next array position
}
/* ==========================================
Done, print values read
========================================== */
for ( int i = 0; i < a.length; i++ )
System.out.println( a[i] );
}
}
|
How to run the program:
|