My program works reading from values that I have stored in an array for valid account numbers. I also have a file that reads the valid account numbers from a text file. I need to read from the text file and not the array.
reads from array
file reader
reads from array
Code:
import java.util.Scanner;
public class ChargeAccount
{
static int[] validChargeAccountNumbers =
{
5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152,
4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231,
3852085, 7576651, 7881200, 4581002
};
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// Ask the user for an account number
System.out.print("Please enter an account number: ");
// Get the number from the user
int number = in.nextInt();
// Check to see if the number is valid
if (ChargeAccount.isValid(number) == true)
{
System.out.println("That account number is valid.");
}
else
{
System.out.println("You did not enter a valid account number.");
}
}
// Check to see if an account number is valid by comparing it to the entries in the array of valid numbers
public static boolean isValid(int number)
{
// Perform sequential search through list of valid account numbers
for (int i = 0; i < validChargeAccountNumbers.length; i++)
{
// Check to see if the number we were given is at the ith position in the list
if (validChargeAccountNumbers[i] == number)
{
return true;
}
}
// If we get down here, then we never found it in the list
return false;
}
}
Code:
mport java.io.*;
class FileReadTest
{
public static void main (String[] args)
{
FileReadTest f = new FileReadTest();
f.readMyFile();
}
void readMyFile()
{
DataInputStream dis = null;
String record = null;
int recCount = 0;
try
{
File f = new File("valid_accounts.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while ( (record=dis.readLine()) != null )
{
recCount++;
System.out.println(recCount + ": " + record);
}
}
// catch io errors from FileInputStream or readLine()
catch (IOException e)
{
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
}
finally
{
// if the file opened okay, make sure we close it
if (dis != null)
{
try
{
dis.close();
}
catch (IOException ioe)
{
}
}
}
}
}
Comment