How do I validate text file contents in Java? - java

I'm creating a program which reads the contents of a .txt file, it validates and then outputs the contents of that file in a nice formatted table. My program currently reads the file and then outputs the content, I'm trying to implement the validation of said file content.
I'll now explain the way my program reads the file:
The .txt contents:
firstname lastname
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
The txt file contains data in this format:
{gamename} : {gamescore} : {minutesplayed}
To read the .txt I use:
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
To then split the data I use this for loop on each letter from a-to-g as shown below:
//~~~~a-line-split~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
To clarify by validation I need to inform the user if data is missing from a line for example if line one had:
gameone : {missing} : 1428
currently I have this simple if statement for each line:
if (bline.length < 3)
{
System.out.println("There is an error in row one!");
}
However I need to the program to know exactly where on each line the data is missing. Not just a generic response of:
System.out.println("There is an error in row one!");
But instead something along the lines of:
System.out.println("There is data missing, row: 1 column: 2");
Full code as requested:
package readfile;
import java.io.*;
import java.util.*;
public class readfile
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String FileN = " ";
String a = " ";
String b = " ";
String c = " ";
String d = " ";
String e = " ";
String f = " ";
String g = " ";
boolean fileExists = false;
File newFile = null;
while(!fileExists)
{
System.out.println("Enter the name of the file you want to open: ");
FileN = scan.nextLine();
newFile = new File(FileN);
fileExists = newFile.exists();
if (!fileExists)
{
System.out.println(FileN + " not found...");
}
}
try {
Scanner scan2;
scan = new Scanner(newFile);
}
catch(FileNotFoundException fnfe) {
System.out.println("sorry but the file doesn't seem to exist");
}
//++++++++++++++=FILE READ=++++++++++++++++++++
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
//+++++++++++++++ARRAYS FOR THE LINES+++++++++++++++++++
//~~~~A-LINE~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
//~~~~B-LINE~~~~//
String[] bline;
bline = b.split(":");
for (int i=0; i<bline.length; i++)
{
bline[i] = bline[i].trim();
//System.out.println(bline[i]);
}
//~~~~C-LINE~~~~//
String[] cline;
cline = c.split(":");
for (int i=0; i<cline.length; i++)
{
cline[i] = cline[i].trim();
//System.out.println(cline[i]);
}
//~~~~D-LINE~~~~//
String[] dline;
dline = d.split(":");
for (int i=0; i<dline.length; i++)
{
dline[i] = dline[i].trim();
//System.out.println(dline[i]);
}
//~~~~e-LINE~~~~//
String[] eline;
eline = e.split(":");
for (int i=0; i<eline.length; i++)
{
eline[i] = eline[i].trim();
//System.out.println(eline[i]);
}
//~~~~f-LINE~~~~//
String[] fline;
fline = f.split(":");
for (int i=0; i<fline.length; i++)
{
fline[i] = fline[i].trim();
//System.out.println(fline[i]);
}
//~~~~g-LINE~~~~//
String[] gline;
gline = g.split(":");
for (int i=0; i<gline.length; i++)
{
gline[i] = gline[i].trim();
//System.out.println(gline[i]);
}
String user = aline [0];
//~~~~~~~~~GAME NAMES~~~~~~~~~~~~~//
//GTA
String gameone = bline [0];
//MINECRAFT
String gametwo = cline [0];
//ASSASSIN'S CREED IV
String gamethree = dline [0];
//PAYDAY2
String gamefour = eline [0];
//WOLFENSTEIN
String gamefive = fline [0];
//FARCRY 4
String gamesix = gline [0];
//~~~~~~~~~~Achievement Score~~~~~~~~~~~~//
//GTA SCORE
String scoreone = bline [1];
//MINECRAFT SCORE
String scoretwo = cline [1];
//ASSASSIN'S CREED IV SCORE
String scorethree = dline [1];
//PAYDAY2 SCORE
String scorefour = eline [1];
//WOLFENSTEIN SCORE
String scorefive = fline [1];
//FARCRY 4 SCORE
String scoresix = gline [1];
//+++++++++++++++++++++TOTAL~~CALC++++++++++++++++++++++//
double totalcount = 79.566; // change to the amount played.
int totalhours = (int)totalcount;
int totalmin = (int)(totalcount*60)%60;
int totalsec = (int)(totalcount*(60*60))%60;
System.out.println("TOTAL TIME PLAYED:");
System.out.println(String.format("%s(hours) %s(minutes) %s(seconds)",
totalhours, totalmin, totalsec));
//~~~~~~~~~~Minutes Played~~~~~~~~~~~~//
//GTA min
String minone = bline [2];
//MINECRAFT min
String mintwo = cline [2];
//ASSASSIN'S CREED IV min
String minthree = dline [2];
//PAYDAY2 min
String minfour = eline [2];
//WOLFENSTEIN min
String minfive = fline [2];
//FARCRY 4 min
String minsix = gline [2];
//~~~~~~~~~GAMES TEST~~~~~~~~~~~~//
System.out.println("\nUSER: "+user);
System.out.println("\nDATA: ");
System.out.println("1: "+gameone+" | score: "+scoreone+"
| minutes played: "+minone);
System.out.println("2: "+gametwo+" | score: "+scoretwo+"
| minutes played: "+mintwo);
System.out.println("3: "+gamethree+" | score: "+scorethree+"
| minutes played: "+minthree);
System.out.println("4: "+gamefour+" | score:
"+scorefour+" | minutes played: "+minfour);
System.out.println("5: "+gamefive+" | score: "+scorefive+"
| minutes played: "+minfive);
System.out.println("6: "+gamesix+" | score: "+scoresix+"
| minutes played: "+minsix);
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two
column "+(i+1));
}
}
}
}
}

if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two column "+(i+1));
}
}
}
Didn't test this but it should work
EDIT:
Looking at your full code bline[2], cline[2]... and so on will give you an Index Out of bounds exception if those values are missing from the file in the first place so before making that call you should do a check first you can create a static method to do the check
public static String getAtIndex(String[] array, int indexToCkeck){
if(indexToCkeck >=array.length){
return "";
}
else{
return array[indexToCkeck];
}
}
So instead of doing bline[2], cline[2] ... use readfile.getAtIndex(bline, 2) so this way if the info is missing it will return an empty string
Also not tested, should be fine though

Use a well tested library like supercsv or any other. This will save you some hours as soon as your text format gets more complex. It also provides a good set of build-in data types to be used to validate each single column of your data. Also you can map the data directly to a POJO which can be handy in some situations.
To load just each row into a map you could do the following:
Prepare your file in stack47220687.txt:
Gamename: Gamescore: Minutestoplay
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
And use something like this
package stack47220687;
import java.io.FileReader;
import java.util.Map;
import org.junit.Test;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.prefs.CsvPreference;
public class HowToReadACSVFile {
private static final CsvPreference COLON_DELIMITED = new CsvPreference.Builder('"', ':', "\n").build();
private static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // gamename
new NotNull(), // gamescore
new NotNull(), // minutestoplay
};
return processors;
}
#Test
public void read() throws Exception {
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(
Thread.currentThread().getContextClassLoader().getResource("stack47220687.txt").getPath()),
COLON_DELIMITED);
// the header columns are used as the keys to the Map
final String[] header = mapReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
Map<String, Object> oneRecordInAMap;
while ((oneRecordInAMap = mapReader.read(header, processors)) != null) {
System.out.println(String.format("lineNo=%s, rowNo=%s, this line stored in a map=%s",
mapReader.getLineNumber(), mapReader.getRowNumber(), oneRecordInAMap));
/**
* oneRecordInAMap.get("Gamescore");
*/
}
} finally {
if (mapReader != null) {
mapReader.close();
}
}
}
}
works with super-csv 2.4.0
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>
and will print
lineNo=2, rowNo=2, this line stored in a map={ Gamescore= 120 , Gamename=Gameone , Minutestoplay= 1428 }
lineNo=3, rowNo=3, this line stored in a map={ Gamescore= 20 , Gamename=Gametwo , Minutestoplay= 10 }
lineNo=4, rowNo=4, this line stored in a map={ Gamescore= 90 , Gamename=Gamethree , Minutestoplay= 800 }
lineNo=5, rowNo=5, this line stored in a map={ Gamescore= 190 , Gamename=Gamefour , Minutestoplay= 2001 }
lineNo=6, rowNo=6, this line stored in a map={ Gamescore= 25 , Gamename=Gamefive , Minutestoplay= 80 }
lineNo=7, rowNo=7, this line stored in a map={ Gamescore= 55 , Gamename=Gamesix , Minutestoplay= 862}
It will also provide meaningful error messages if your format is not correct.

Related

Only outputting last line of loop

import java.io.*;
import java.util.Random;
public class LargeDataset {
public static void main(String[] args) throws Exception {
File file = new File("src/Salary.txt");
if (file.exists()) {
System.out.print("Sorry this file already exists.");
System.exit(0);
}
String firstName = "";
String lastName = "";
String rank = "";
double salaryRange = 0.0;
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
{
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
}
public static String generateRandomRank() {
String[] rank = {"assistant", "associate", "full"};
Random random1 = new Random();
return rank[random1.nextInt(3)];
}
public static double generateSalary(double minSalary, double maxSalary) {
double randomSalary = minSalary + Math.random() * (maxSalary - minSalary);
return randomSalary;
}
}
Hi everyone. I have a program that generates 1000 lines of text and saves it into a file named Salary. The format of each line is: firstNamei, lastNamei, a random rank, and a random salary that is suited to the rank. However when I run this program it only outputs the 1000th line of the loop. I noticed however, when I don't put the PrintWriter in the try statement and close it after the loop by myself, it runs fine and generates all 1000 lines. Why is it only generating the last line based on how it is right now though?
You should open your PrintWriter once, and then write to it many times from your loop, not the other way around:
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
You should use the above pattern instead of what you have. If you want an exact fix to your current code, then you may try opening the PrintWriter in append mode:
for (int i=1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(new FileOutputStream(file, true)) {
// same logic
}
}
This should also work, because now, even though you create a new PrintWriter for each iteration of the loop (inefficient), you open the underlying file in append mode, so each new line should get written properly.
Every time that you are iterating through your 1000 you are creating a new file
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
...
}
move it before the loop
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
}
}

Populating Array from File input

I'm working on a pokemon battle simulator, (basically pokemonshowdown gen1), trying to automate making the pokemon array, but running into a Scanner problem. File is formatted as: Name.Type1.Type2.hp.attack.defense.special.speed.list of learnable moves. So:
Aerodactyl.Flying.Rock.80.105.65.60.130.Agility,Bide,Bite,Double-Edge,Double Team,Dragon Rage,Fire Blast,Fly,Hyper Beam,Mimic,Rage,Razor Wind,Reflect,Rest,Sky Attack,Substitute,Supersonic,Swift,Take Down,Toxic,Wing Attack.
I've gotten a method working for both my typeArray and moveArray but for some reason using basically the same loop the scanner is returning empty tokens instead of what's in the file.
Exception:
0 Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Controller.initPokemonArray(Controller.java:169)
at Controller.<init>(Controller.java:29)
at Driver.main(Driver.java:15)
Here's the whole method, it's throwing the error at the parseInt call for hp.
private Pokemon[] initPokemonArray() {
Pokemon[] pokemonArray = new Pokemon[83];
try {
Scanner inputScan = new Scanner(new File("src/pokemon")).useDelimiter(".");
String name = "";
Type type1 = typeArray[0];
String inputType1 = "";
Type type2 = typeArray[0];
String inputType2 = "";
int hp = 0;
int atk = 0;
int def = 0;
int spc = 0;
int spe = 0;
String[] lm = {};
Move[] learnableMoves;
int counter = 0;
while (counter < 83) {
System.out.print(counter);
if (inputScan.hasNextLine()) {
name = inputScan.next();
System.out.println(name+" ");
//System.out.print("name");
inputType1 = inputScan.next();
for (int i = 0;i < 16;i++)
if (inputType1.equals(typeArray[i].toString()))
type1 = typeArray[i];
System.out.println(type1.toString()+" ");
inputType2 = inputScan.next();
for (int i = 0;i < 16;i++)
if (inputType2.equals(typeArray[i].toString()))
type2 = typeArray[i];
System.out.println(type2.toString()+" ");
hp = Integer.parseInt(inputScan.next());
System.out.println(hp+" ");
atk = Integer.parseInt(inputScan.next());
System.out.println(atk+" ");
def = Integer.parseInt(inputScan.next());
System.out.println(def+" ");
spc = Integer.parseInt(inputScan.next());
System.out.println(spc+" ");
spe = Integer.parseInt(inputScan.next());
System.out.println(spe+" ");
lm = inputScan.next().split(",");
System.out.println();
}
//TODO move this to private helper method
learnableMoves = new Move[lm.length];
for (int i = 0;i < 160;i++) {
for (int j = 0;j < lm.length;j++) {
if (lm[j] == moveArray[i].getName())
learnableMoves[j] = moveArray[i];
}
}
pokemonArray[counter] = new Pokemon(name,type1,type2,hp,atk,def,spc,spe,learnableMoves);
counter++;
}
inputScan.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pokemonArray;
}
DISCLAIMER: this is a project for my java 2 course and also my first post on here so I don't know exactly what I'm supposed to do so just letting it be known down here.
The useDelimiter() method takes the passed String as regex value.https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useDelimiter-java.lang.String-. A period has a specific meaning in regex. To get the specific character "." use this.
Scanner inputScan = new Scanner(new File("src/pokemon")).useDelimiter("\\.");

Writing to File Error in Java

I am trying to write to a file (leaders.txt) and I am having an issue with the way the data I have calculated is showing in the file.
import java.io.*;
import java.util.*;
public class readStats {
public static int getStat(String letter, String stats) {
int count = stats.length() - stats.replace(letter, "").length();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
String hitsLeader = null;
String walksLeader = null;
String hitsByPitchLeader = null;
String strikeoutsLeader = null;
String battingAverageLeader = null;
int maxHits = 0;
int maxWalks = 0;
int maxHitsByPitch = 0;
int maxStrikeouts = 0;
int maxBa = 0;
java.io.File file = new java.io.File("stats.txt");
Scanner input = new Scanner(file);
//Find out number for each category
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(" ");
int hits = getStat("H", parts[1]);
int outs = getStat("O", parts[1]);
int walks = getStat("W", parts[1]);
int hitsByPitch = getStat("P", parts[1]);
int strikeouts = getStat("K", parts[1]);
int sacrifices = getStat("S", parts[1]);
int totalAtBats = hits + outs + strikeouts;
double ba = ((double)hits/(double)totalAtBats );
//System.out.println("Player " + parts[0]);
if (hits > maxHits) {
maxHits = hits;
hitsLeader = parts[0];
}
if (walks > maxWalks) {
maxWalks = walks;
walksLeader = parts[0];
}
if (hitsByPitch > maxHitsByPitch) {
maxHitsByPitch = hitsByPitch;
hitsByPitchLeader = parts[0];
}
if (strikeouts > maxStrikeouts) {
maxHits = hits;
strikeoutsLeader = parts[0];
}
if (ba > maxBa) {
maxHits = hits;
battingAverageLeader = parts[0];
}
//Create PrintWriter
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
// Print LEAGUE LEADERS to leaders.txt
output.println(parts[0]);
output.printf("BA: %.3f", ba);
output.println("H: " + hits);
output.println("BB: " + walks);
output.println("K: " + strikeouts);
output.println("HBP: " + hitsByPitch);
output.println("");
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
}
}
}
Output in leaders.txt
Pudge
BA: 0.450H: 9
BB: 2
K: 8
HBP: 1
LEAGUE LEADERS
BA: Pudge
H: Piazza
BB: Griffey
K: Pudge
HPB: Griffey
Stats.txt
Griffey HHOHOKWOHKSPOOWSHHWWWWWWW
Piazza OOHHHKPSOHOOHWWHOSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
Pudge HHHHKOOHHHSWWHHOPKKKKKKK
Desired Output
Griffey
BA: 0.462
H: 6
BB: 9
K: 2
HBP: 1
Piazza
BA: 0.833
H: 35
BB: 2
K: 1
HBP: 1
Pudge
BA: 0.450
H: 9
BB: 2
K: 8
HBP: 1
I need the output to display all three of the players that are associated in the file stats.txt, not just one.
Start the printer before the while loop and close it afterwards.
The league leaders should be printed only once.
Move those after the loop when you have the numbers of each player compared.
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
while (input.hasNextLine()) {
...
}
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
Edit: Add
output.println();
after
output.printf("BA: %.3f", ba);
printf doesn't start a new line.

How do I get the function to print out a 2D array into two files in java?

My goal is to take a file with names and numbers, the first row will name the columns, the rows following will be the data. Column 0 will have the first name and 1 will have the last name which will be combined. Columns 2, 3, and 4 will contain 3 numbers that will be averaged together, columns 5 to 11 will also contain numbers that will be averaged together. This will be the test data:
first, last, #1, #2, #3, #4, #5, #6, #7, #8, #9, #10
Dan, Smith, 56, 58, 55, 66, 44, 78, 60.33, 52.33, 70.66, 44
Sam, Will, 77, 88, 55, 99, 77, 10, 62, 65, 59, 62
From here the two output files will contain the same information, the second will have the information spaced out in a neater fashion. What I want the out puts to be are:
name, exam score,hw score,min score
Dan Smith, 56.33, 62.66, 56.33
Sam Will, 73.33, 62, 62
This line will just be used for the second output file:
out.printf("%20s: %10.2f, %8.2f, %9.2f\r\n",name, average1, average2, smallestaverage);
My code is as follows, I tried to test and see if I could print out parts of the data using a for loop but would only receive the original values set for the two variables:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.PrintWriter;
public class compute_grades {
public static void process_grades(String input_name, String csv_name, String pretty_name) {
String[][] data = read_spreadsheet(input_name);
String csvname = "csv_name.txt";
String pretty = "pretty_name.txt";
PrintWriter out = null;
try {
out = new PrintWriter(input_name);
} catch (Exception e) {
System.out.printf("Error: failed to open file %s.\n", input_name);
System.exit(0);
}
String first = "dog";
String last = "dat";
for (int i = 0; i < data.length; i++) {
first = data[i][0];
last = data[i][1];
}
System.out.println(first + last);
}
public static String[][] read_spreadsheet(String filename) {
ArrayList < String > lines = read_file(filename);
if (lines == null) {
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++) {
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList < String > read_file(String filename) {
File temp = new File(filename);
Scanner input_file;
ArrayList < String > result = new ArrayList < String > ();
try {
input_file = new Scanner(temp);
} catch (Exception e) {
System.out.printf("Failed to open file %s\n", filename);
return result;
}
while (input_file.hasNextLine()) {
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
System.out.printf("Please enter the name of the input file: ");
String input_name = in .next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in .next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in .next();
process_grades(input_name, csv_name, pretty_name);
System.out.printf("\n\nExiting...\n");
}
}
I don't get the difference between your two output files but I think your process Method should look like this:
public static void process_grades(String input_name, String csv_name, String pretty_name) {
String[][] data = read_spreadsheet(input_name);
PrintWriter out = null;
try {
out = new PrintWriter(csv_name);
} catch (Exception e) {
System.out.printf("Error: failed to open file %s.\n", input_name);
System.exit(0);
}
// print header
out.printf("name, exam score,hw score,min score\r\n");
// go throu all the other rows
for (int row = 1; row < data.length; row++) {
// get Name
String name = data[row][0] + " "+ data[row][1];
// avg the next three cols
double average1 = 0;
for(int col = 2; col < 5; col++)
average1 += Double.parseDouble(data[row][col].trim());
average1 /= 3;
// avg the next seven cols
double average2 = 0;
for(int col = 5; col < 12; col++)
average2 += Double.parseDouble(data[row][col].trim());
average2 /= 7;
//get min score
double smallestaverage = Math.min(average1,average2);
// print the content
out.printf("%20s: %10.2f, %8.2f, %9.2f\r\n",name, average1, average2, smallestaverage);
}
// flush the output and close the writer
out.flush();
out.close();
}

retrieve phone number from text file using indexOf

I have a text file which has details like date,time,phone number, etc. I am trying to retrieve these details using the java indexOf concept. However, the digits in the phone number would change depending on the type of call.
How can I improve the code so I am able to retrieve every phone number from the file. Here's what I've been trying :
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String getIndex="";
while ((line = reader.readLine()) != null) {
line = line.replaceAll("[\\s]+", " "); //remove all large spaces from the file.
/*
the dialledNo is chosen with the help of a combo box.
calculating the start and end index in order to print the dialled no.
*/
int startIndex = getIndex.indexOf(dialledNo);
int endIndex = getIndex.indexOf(" ", startIndex);
strDialedNo= (startIndex + "," + endIndex);
And the code to retrieve the number is mentioned below :
String[] arrDialedNo = strDialedNo.split(",");
int DialedNoStart = Integer.parseInt(arrDialedNo[0]);
int DialedNoEnd = Integer.parseInt(arrDialedNo[1]);
DialedNo = line.substring(DialedNoStart, DialedNoEnd);
This is how my text file looks like:
0356 524 000 8861205063 12/03 18:59 00:08 01:20
0357 524 000 9902926868 12/03 20:01
0373 511 000 09886863637 13/03 11:46 01:01 02:40 S
0376 504 000 9845014967 13/03 11:46 00:11 01:20
0382 508 000 04443923200 13/03 12:04 03:11 04:80 S
0411 516 000 8884103111 13/03 16:25 01:03 01:20
This should work,
String[] b = line.split(" ");
String phoneNumber = null;
for (String x : b) {
boolean z = false;
if (x.length() == 10) {
char[] c = x.toCharArray();
for (char g : c) {
if (Character.isDigit(g)) {
z = true;
} else {
z = false;
break;
}
}
} else {
z = false;
}
if (z) {
phoneNumber = x;
}
}
/* Easiest way to to retrieve Phone number from Text file using Java */
package TestProject.EndToEnd;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("//File//Path//");
List<Object> ph = new ArrayList<Object>();
Scanner scan = new Scanner(file);
while(scan.hasNext()) {
scan.next();
if(scan.hasNextBigInteger()) {
ph.add(scan.next());
}
}
for (int i = 0; i < ph.size(); i++) {
if(ph.get(i).toString().length()==10) {
System.out.println(ph.get(i));
}
}
}
}

Categories

Resources