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 -
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;
-
}
-
}
-
file reader -
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)
-
{
-
}
-
}
-
}
-
}
-
}
-
Ouch. Then you are one frustrated kid.
Still, your code looks good. All you need is the read-file bit and you're done.
Did you ever bother to read that link I sent?
This is a simplified bit of code that might work for you, but it'll never fly in a production environment where people seem to put all kinds of junk in files. The problem is, of course, in error detection and reporting: - try {
-
Scanner s = new Scanner(new File(fileName));
-
-
while(s.hasNextInt())
-
validChargeAccountNumbers.add(s.nextInt());
-
} catch (FileNotFoundException e) {
-
e.printStackTrace();
-
}
58 6314
Try building a method similar to ReadMyFile(), which returns a collection of valid accounts. The type of collection would, of course, depend on how you are planning to use the account numbers. -
import java.util.Set;
-
import java.util.HashSet;
-
-
public Set<Integer> ReadMyFile
-
{
-
HashSet<Integer> result = new HashSet<Integer>;
-
-
...
-
-
while( !eof )
-
{
-
...
-
result.add(new Integer(validAccount));
-
}
-
-
return result;
-
}
Hopefully this helps a little.
I just want it to basically check from the validAccounts.txt file to see if the users input is a valid account.
Do you want to reload the file every time for the check, or just read the thing once?
Right now all you have are miscellaneous code bits that sort of solve your problem.
I take it that your assignment is to write a one-shot test to see if the account number is valid?
If you don't like the approach of returning a collection, then think procedurally.
You might use your current file read routine to test while reading - if no match is found by end-of file, then there is no match. (BTW, I notice that you are reading lines, not integer values. Were you planning on doing a comparison of strings or integers?)
You might hoist the file-read code to your isValid() method. Or even into the main routine.
If you need help converting text strings into integers, look up the documentation on Integer.decode(String).
Luck!
I have a two part assignment. -
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;
-
}
-
}
-
this works great. Now the second part is to read the valid accounts stored in the array above from a text file(valid_accounts.txt)
Well, you've made a good start at your reader code. Don't throw that away.
You already know that you need to replace the static instantiation of the account number array.
First, have you got a strategy? Will you look at the file until found, or will you read the entire file and then see if the value is there? This determines how you will write your program.
Second, have you looked at using any of the java.util collection classes to manage the account numbers? Or hasn't your instructor introduced you to template classes, yet?
Third, if you are lost, try pseudo-coding your answer - solve the problem with words first. Then you can write Java code to implement your solution.
Lastly, has your instructor given you any out-of-band information, like maximum file size, or some such? This is important, because the kinds of considerations in production software are a little tougher than are usually applied to students' assignments.
Cheers!
Ok i have it reading from the text file now but it is only outputing "the account you entered is invalid even when I input the correct account number. -
import java.io.BufferedReader;
-
import java.io.FileReader;
-
import java.io.IOException;
-
import java.util.Scanner;
-
import java.util.Vector;
-
-
public class ChargeAccount
-
{
-
static Vector<Integer> validChargeAccountNumbers = new Vector<Integer>();
-
-
-
public static void main(String[] args)
-
{
-
//load the file
-
readMyFile("valid_accounts.txt");
-
-
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 (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 vector validChargeAccountNumbers
-
public static boolean isValid(int number)
-
{
-
return validChargeAccountNumbers.contains(number);
-
}
-
-
public static void readMyFile(String nameFile)
-
{
-
String record = null;
-
BufferedReader reader = null;
-
FileReader fr = null;
-
int recCount = 0;
-
-
// Code to read the file and store each account into the vector
-
// validChargeAccountNumbers
-
-
}
-
}
-
Excellent.
So now all you have to do is read from the file into your Vector, right?
The code is essentially the same as that you had earlier.
You're using a Scanner to read from the System.in stream, right?
What's wrong with using a Scanner to read from your account numbers file?
The only trick is detecting EOF, right? Scanner.nextInt() throws a java.util.NoSuchElementException exception on end-of-input. The page is here.
So the control code will look something like: -
try
-
{
-
while(true)
-
{
-
value = myScanner.nextInt();
-
validChargeAccountNumbers.add(value);
-
}
-
}
-
catch (NoSuchElementException exception)
-
{
-
// EOF is legitimate; all others will pass up the stack
-
}
Do you think you can do the rest?
actually no, I am late with this project. I have been working on it and have fallen behind in my other classes.
you mean something like this: -
import java.io.*;
-
import java.util.Vector;
-
-
public class readMyFile
-
{
-
public static void main(String[] args)
-
{
-
DataInputStream dis = null;
-
String record = null;
-
int recCount = 0;
-
Vector<String> vAccounts = new Vector<String>();
-
-
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 )
-
{
-
vAccounts.add(record);
-
recCount++;
-
System.out.println(recCount + ": " + record);
-
}
-
}
-
-
// catch io errors from FileInputStream or readLine()
-
catch (IOException e)
-
{
-
System.out.println("IOException error!" + e.getMessage());
-
}
-
-
finally
-
{
-
-
// if the file opened okay, make sure we close it
-
if (dis != null)
-
{
-
try
-
{
-
dis.close();
-
}
-
catch (IOException ioe)
-
{
-
}
-
}
-
}
-
}
-
}
-
Ouch. Then you are one frustrated kid.
Still, your code looks good. All you need is the read-file bit and you're done.
Did you ever bother to read that link I sent?
This is a simplified bit of code that might work for you, but it'll never fly in a production environment where people seem to put all kinds of junk in files. The problem is, of course, in error detection and reporting: - try {
-
Scanner s = new Scanner(new File(fileName));
-
-
while(s.hasNextInt())
-
validChargeAccountNumbers.add(s.nextInt());
-
} catch (FileNotFoundException e) {
-
e.printStackTrace();
-
}
lol very confused old man (44). I will try that.
Eeeep, that makes me ancient (48).
Do you understand what the code example does?
it looks like it reading from the file validChargeAccountNumber
ok so it should be in the readMyFile method?
Yep.
So that's probably the core of your method "ReadMyFile()".
What is important is how you incorporate it.
Since you're a student, I assume that you don't have any strong idea of exception handling, and how to use it. That's why the example (chicken-sh*t) exception handler.
At some level you'll have to deal with I/O errors in your program. You might just be able to declare all your methods as "throws Exception", and that's it. I really don't know what your instructor's exception handling requirements are.
Hopefully you can test and you'll be done in a couple minutes. Your post #7 looks pretty good, otherwise.
i get the error when i do it like that:
ChargeAccount.java:54: cannot find symbol
symbol : class File
location: class ChargeAccount
Scanner s = new Scanner(new File());
^
ChargeAccount.java:58: cannot find symbol
symbol : class FileNotFoundException
location: class ChargeAccount
catch (FileNotFoundException e)
^
2 errors
Ok, good start.
Did you remember to import the requisite classes. Either with the blanket imports: - import java.io.*;
-
import java.util.*;
or explicitly: - import java.io.File;
-
import java.io.FileNotFoundException;
-
import java.util.Scanner;
BTW, is this your first or second Java program? *friendly-laugh*
he wanted us to us throws Exepction
not to sound ingorant but this is my second time taking the class. I got a D before. It is intro to Java.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Vector;
Im getting the scanner error now with this:
try {
Scanner s = new Scanner(new File());
while(s.hasNextInt())
validChargeAccountNumbers.add(s.nextInt());
}
catch (IOException ioe)
{
symbol : class File
location: class ChargeAccount
Scanner s = new Scanner(new File());
Sorry, was distracted by work there.
Try changing the declaration of your reader function to: - public static void readMyFile(String nameFile)
-
throws Exception
and drop the try/catch block.
ok did that and now it give me this error:
unreported exception java.lang.Exception; must be caught or declared to be thrown
readMyFile("valid_accounts.txt");
So add the same annotation to your Main function.
Either that, or Main will have to wrap all your code in a try/catch block, and handle the reporting. Does that make sense?
I appreciate all you help! here is the code i have now -
import java.io.BufferedReader;
-
import java.io.FileReader;
-
import java.io.IOException;
-
import java.util.Scanner;
-
import java.util.Vector;
-
-
public class ChargeAccount
-
{
-
static Vector<Integer> validChargeAccountNumbers = new Vector<Integer>();
-
-
-
public static void main(String[] args)
-
{
-
//load the file
-
readMyFile("valid_accounts.txt");
-
-
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 (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 vector validChargeAccountNumbers
-
public static boolean isValid(Integer number)
-
{
-
return validChargeAccountNumbers.contains(number);
-
}
-
-
public static void readMyFile(String nameFile) throws Exception
-
{
-
-
String record = null;
-
BufferedReader reader = null;
-
FileReader fr = null;
-
int recCount = 0;
-
-
-
//code to read the file and store each account into the vector validChargeAccountNumbers
-
{
-
Scanner s = new Scanner(new File());
-
while(s.hasNextInt())
-
validChargeAccountNumbers.add(s.nextInt());
-
}
-
}
-
}
-
the ERROR:
ChargeAccount.java:54: cannot find symbol
symbol : class File
location: class ChargeAccount
Scanner s = new Scanner(new File());
^
The constructor for the File object in line 54 needs a file name, right?
BTW, lines 46-49 aren't doning anything useful, and the braces at lines 53 and 57 are extraneous.
ok did all that now I get this:
ChargeAccount.java:48: cannot find symbol
symbol : class File
location: class ChargeAccount
Scanner s = new Scanner(new File("valid_accounts.txt"));
thats right if a method have the throws then the main has to have it!
with this its like stuck in an infinite loop right?
Scanner s = new Scanner(new File()); while(s.hasNextInt())
validChargeAccountNumbers.add(s.nextInt());
}
not really. take a look at the Scanner.hasNextInt() method, you'll understand.
ok it just took a long time to compile. Its still doing what it originally did. any account number whether true or false it output false. So my guess is its not reading the file right?
how can I store it after I read the valid_accounts.txt?
What are you using to run Java? Just the command line compiler?
I just tried your program, edited as I observed, and it works just fine. Something else is going on.
So, you can interrogate the validChargeAccountNumbers array by using - for (int ix = 0; (ix < validChargeAccountNumbers.size()); ix++)
-
System.out.println("acct[" + ix + "] = " + validChargeAccountNumbers.get(ix));
Hmmm.
I haven't heard of it.
I'm using the Java 1.6 development environment from Sun underneath the Eclipse IDE.
As I noted - your program works for me. And when I use an incorrect file name, I get an exception telling me its not there.
Are you certain that the only thing in your valid_accounts file are integers separated by spaces?
I expect that if you have commas or other debris in there, you might have troubles.
Yes it runs but when i enter 5658845(a valid account number) it displays "You did not enter a valid account number." when it should display "That account number is valid."
Did the account number show up in your diagnostics list?
this is in valid_accounts.txt
5658845
4520125
7895122
8777541
8451277
1302850
8080152
4562555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002
this is what shows up:
----jGRASP exec: java ChargeAccount
Please enter an account number: 5658845
You did not enter a valid account number.
----jGRASP: operation complete.
Odd, it looks like the first in the list.
At this point, I'm not sure why you're not seeing the correct response.
Try printing out the actual value you read in. - System.out.println("number = " + number);
yeah its the first...Have it memorized now lol. I used the System.out.println("number = " + number); got error number symbol not found. then i used the
//code to read the file and store each account into the vector validChargeAccountNumbers
{
Scanner s = new Scanner("valid_accounts.txt");
while(s.hasNextInt())
validChargeAccountNumbers.add(s.nextInt());
for (int ix = 0; (ix < validChargeAccountNumbers.size()); ix++) System.out.println("acct[" + ix + "] = " + validChargeAccountNumbers.get(ix));
System.out.println("number = " + validChargeAccountNumbers);
}
and i get
----jGRASP exec: java ChargeAccount
number = []
Please enter an account number: 5658845
You did not enter a valid account number.
so based on number = [] its not reading the file right?
Well, if the list didn't print, then something is wrong.
Look at where you are creating the Scanner object.
Do you know what that means in the documentation?
The line should be: - Scanner s = new Scanner(new File("valid_accounts.txt"));
Otherwise, it will try to scan the input string "valid_accounts.txt", which, of course, contains no valid integer values.
Why did you eliminate the "new File" from the code I posted?
ok lets start fresh. This is my orignal program: -
import java.util.Scanner;
-
-
public class ChargeAccount1
-
{
-
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 (ChargeAccount1.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;
-
}
-
}
-
return false;
-
}
-
}
-
because it gave the error:
ChargeAccount.java:48: cannot find symbol
symbol : class File
location: class ChargeAccount
Scanner s = new Scanner(new File("valid_accounts.txt"));
^
1 error
Actually go to the code from post #28, and fix line #54 by placing the correct file name in the line where you create the Scanner.
That gave you the error "Can't find class File", right?
Well, you need to import File to resolve that - specifically the class java.io.File.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Thomas Matthews |
last post by:
Is there anything technically wrong with the code below?
I compiled it with g++ 3.3.1 and it executes with no errors.
I compiled it with bcc32 5.6 and it executes with "This
program has performed...
|
by: cherry |
last post by:
Dear All,
I have written a program in sharepoint, in which will call a Web
Service of another Sharepoint portal server so that documents from
sharepoint portal server A can push document to...
|
by: ComicCaper |
last post by:
Hi all,
I use a quiz program that accepts a text file for questions and answers
in this format:
Question
Answer1 <----is the correct answer. Quiz randomizes answers.
Answer2
Answer3...
|
by: Glenn Graham |
last post by:
My web download program stopped working when IE7 beta 1-3 was installed.
Error when calling OpenRequest in CHttpConnection. The Error is Created by
ASSERT(hFile != NULL) in mehtod...
|
by: jisha |
last post by:
i want to get code for a program in visual c++ where :
1]take the name of directory say DIR
2]get a file ,say IN from that directory which has 3 column (say X, Y and Z) and many rows( display this...
|
by: gdarian216 |
last post by:
I am doing a multi file program and I got it to work correctly in a single file but when I split it up it isn't working properly. I keep getting errors when i compile. Can anyone help me figure out...
|
by: gdarian216 |
last post by:
I am writing a multifile program and it worked when it was all in one file. I have gotten all of the errors out of the program except when I go to output the change the quarters are right but the...
|
by: sadanand |
last post by:
Hi,
I am a beginer to perl progmig.
When I run the following program..
use File::Find;
use File::Stat;
use Time::Local;
|
by: rajak20pradeep |
last post by:
Hello,
i cannot solve this program.
Q. Write a program to find and count article(a.an ,the) in a text file .
|
by: sunny |
last post by:
Hi all
We have a pdf user manual which we open when client clicks on help
button. some of our clients have the issue that it does not open the
file and it says file not found. checked with...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
| |