This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading an array of numbers from a txt file  RSS feed

 
Mark Jones
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am currently working on a lottery programme which requires me to search a *.txt to find winners of a lottery. I have addapted my program to find the lowest number from a text file but im not sure how to adapt it to find 4 different numbers and come up with a winner.
this is what i have so far:
import java.io.*;
import javax.swing.*;
public class FileTest {
private static String[] names = new String[20];
private static long[] userids = new long[20];
private static double[] credits = new double[20];
private static int linecount = 0; // counts lines of the file
private static int counter = 0; // counts file records
public static void main(String[] args) {
String fname = JOptionPane.showInputDialog("Enter your file name/path");
int lines = readFile(fname);
int position = 0;
double lowestcredit = credits[0];
for (int i = 1; i < counter; i++) {
if (credits[i] < lowestcredit) {
lowestcredit = credits[i];
position = i;
}
}
JOptionPane.showMessageDialog (null, "The person with least credits is\n" + names [position] + " with " + lowestcredit + " credits");
System.exit(0);
}
public static void process(String l) {
if (counter >=20) {
System.out.println ("Arrays are full!");
return;
}
if (linecount % 3 == 0) {
names [counter] = l;
}
else if (linecount % 3 == 1) {
userids[counter] = Long.parseLong(l);
}
else {
credits[counter] = Double.parseDouble (l);
counter++; //this is the end of the record
}
linecount++;
}
public static int readFile(String filenm) {
int count = 0;
FileReader fileread;
String line = "xxxx";
try {
fileread = new FileReader(filenm);
}
catch (IOException e) {
errorMessage("Error opening file");
return 0;
}
BufferedReader br = new BufferedReader(fileread);
while (line != null) {
try {
line = br.readLine();
if (line != null) {
process(line);
count ++;
}
}
catch (IOException e) {
errorMessage("Error reading file");
line = null;
}
}
try {
br.close();
fileread.close();
}
catch (IOException e) {
errorMessage("Error closing file");
}
return count;
}
public static void errorMessage(String m) {
JOptionPane.showMessageDialog(null, m, "Error", JOptionPane.ERROR_MESSAGE);
}
}
The format of the text file is:
Mark Jones
01332 556489
12 16 24 29
Frank Butcher
01332 548787
16 25 36 42
I need to input the winning numbers and search the text file to see if anyone matches 2, 3 or 4 numbers. Anyone have any ideas that would be great. Thank you...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!