I'm setting up a program to sort information including names, addresses, phone numbers, and emails. But there is no format for the user's input and I am having trouble splitting up the information. Any tips?
I've tried using a combination of if/else statements and I have to use a for loop to go through all the information.
This is what is given to me
String[] TheNeededData = new String[]{"Alexa Pope/P.O. Box 435 5461 Euismod Avenue1-182-963-3500 blandit.congue#utcursus.co.uk",
"Kylynn Allen/8402 Justo St.1-357-430-1865morbi.tristique#lectus.org","Moana Cannon 522-1918 Quisque Rd. 1-752-893-8123 enim.mi#idsapienCras.edu"};
This is what I tried
int count;
public TheData(String TheString)
{
int x = TheString.length();
for(int y = 0; y<x; y++)
{
String z = String.valueOf(TheString.charAt(y));
if(z.equals("/"))
System.out.println(TheString.substring(0,y));
else
{
if(count == 1)
if(z.equals(" "))
{
System.out.println(TheString.substring(0,y));
count++;
}
if(count == 0)
if(z.equals(" "))
{
count ++;
}
}
}
}
This was the output
Alexa Pope
Alexa Pope/P.O.
Kylynn Allen
Kylynn Allen/8402
Moana Cannon 522-1918
I expected to have the first few names be printed using a substring to the charAt("/"), then I tried to find the last name by identifying the first two spaces, but it printed more than just the names along with printing the names more than once.
As you do not know what is the data format I would try to iterate over some or all the entries and adjust patterns in the process.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.stream.Collectors.toList;
public class Main {
private static final Pattern NAME_REGEX =
Pattern.compile("^([A-Z]+ [A-Z]+ ).*$", CASE_INSENSITIVE);
private static final Pattern EMAIL_ADDRESS_REGEX =
Pattern.compile("^.* ([A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}).*$", CASE_INSENSITIVE);
private static final Pattern PHONE_NUMBER_REGEX =
Pattern.compile("^.*(\\d-\\d{3}-\\d{3}-\\d{4}).*$", CASE_INSENSITIVE);
public static void main(String[] args) {
var data = new String[]{
"Alexa Pope/P.O. Box 435 5461 Euismod Avenue1-182-963-3500 blandit.congue#utcursus.co.uk",
"Kylynn Allen/8402 Justo St.1-357-430-1865morbi.tristique#lectus.org",
"Moana Cannon 522-1918 Quisque Rd. 1-752-893-8123 enim.mi#idsapienCras.edu"};
for (var entry : cleanUpData(data)) {
System.out.println("\n" + entry);
var name = findMatch(entry, NAME_REGEX).orElse("");
var phoneNumber = findMatch(entry, PHONE_NUMBER_REGEX).orElse("");
entry = entry.replace(phoneNumber, " ");
var emailAddress = findMatch(entry, EMAIL_ADDRESS_REGEX).orElse("");
System.out.println("Name: " + name);
System.out.println("Email: " + emailAddress);
System.out.println("Phone: " + phoneNumber);
}
}
private static List<String> cleanUpData(String[] data) {
return Arrays.stream(data).map(s -> s
.replace("/", " ")
.trim()
.replaceAll(" +", " ")
).collect(toList());
}
private static Optional<String> findMatch(String entry, Pattern pattern) {
Matcher matcher = pattern.matcher(entry);
if (!matcher.find()) {
return Optional.empty();
}
try {
return Optional.of(matcher.group(1));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
}
Output:
Alexa Pope P.O. Box 435 5461 Euismod Avenue1-182-963-3500 blandit.congue#utcursus.co.uk
Name: Alexa Pope
Email: blandit.congue#utcursus.co.uk
Phone: 1-182-963-3500
Kylynn Allen 8402 Justo St.1-357-430-1865morbi.tristique#lectus.org
Name: Kylynn Allen
Email: morbi.tristique#lectus.org
Phone: 1-357-430-1865
Moana Cannon 522-1918 Quisque Rd. 1-752-893-8123 enim.mi#idsapienCras.edu
Name: Moana Cannon
Email: enim.mi#idsapienCras.edu
Phone: 1-752-893-8123
Related
I have an assignment which I have to program that creates a standings table from match list input. I used the word "infinite" because input size is unknown so I have to create a program that works until there's no matches left. I created a football class for this(input contains 2 other sports and their own matches and teams indicating the sports type with first letter of the sport with "F, B, V" for example, they're only different in scoring part, so I though if I can make football work, I can make anything else work) that contains everything required in standings table, and methods for match results which looks like this:
public class Football {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int Score;
private int wins;
private int losses;
private int MatchCount;
private int draws;
public void teamValues(String teamName, int Sgoals, int Rgoals) {
this.teamName = teamName;
this.scoredGoals = Sgoals;
this.receivedGoals = Rgoals;
}
public void matched() {
MatchCount++;
}
public void winner() {
wins++;
}
public void draw() {
draws++;
}
public void loser() {
losses++;
}
public void winScore() {
Score += 3;
}
public void drawScore() {
Score += 1;
}
public String showTeams() {
return (teamName + " " + MatchCount + " " + wins + " " + draws + " " + losses + " " + scoredGoals+":"+receivedGoals + " " + Score);
}
}
And in main class I'm calling methods in if blocks to calculate wins, score, matches count etc. And main looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner scan = new Scanner(file);
String fileString = "";
Football teams[] = new Football[2];
HashSet<String> teamsArray = new HashSet<String>();
while(scan.hasNextLine()) {
fileString = scan.nextLine();
String[] match = fileString.split("\\t|:");
if(match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
teams[0] = new Football();
teams[0].teamValues(match[1], team1score, team2score);
teams[1] = new Football();
teams[1].teamValues(match[2], team2score, team1score);
teams[0].matched();
teams[1].matched();
if(team1score>team2score) {
teams[0].winner();
teams[1].loser();
teams[0].winScore();
}
if(team1score==team2score) {
teams[0].draw();
teams[1].draw();
teams[0].drawScore();
teams[1].drawScore();
}
if(team1score<team2score) {
teams[1].winner();
teams[0].loser();
teams[1].winScore();
}
String team0 = teams[0].showTeams();
String team1 = teams[1].showTeams();
teamsArray.add(team0);
teamsArray.add(team1);
}
}
scan.close();
}
}
Since the input is static, I used arrays to work around. My problem with my code is I cant find a way to store my teams without duplicates and the variables that comes within and update whenever that team has another match.
I tried;
Storing them in a 2D string array but since the amount of teams is unknown I think it won't be a healthy way to approach to the problem.
Storing them in a String[] array list, which ended up storing the adresses instead of the values of the teams.
Set which I still use to check if at least the methods are working as intended.
It feels like I hit the wall with this program and I need to start over, so any kind of advice is appreciated.
Here's an example of input and output:
Input:
Home Team Guest Team H : G
F Manchester U. Chelsea 2 : 2
F Liverpool Manchester City 3 : 2
F Leicester City Everton 1 : 3
V Team A Team B 3 : 0
F Tottenham Liverpool 3 : 1
B Team B Team A 90 : 96
F West Ham Manchester U. 2 : 1
F Arsenal Manchester City 0 : 2
F Chelsea Arsenal 3 : 3
Output:
Name Matches Wins Draw Lose Scored:Received Score
1. Manchester U. 10 6 2 2 27:22 20
2. Arsenal 10 6 2 2 25:24 20
3. Chelsea 10 5 3 2 28:20 18
4. Liverpool 10 4 4 2 22:19 16
5. Tottenham 10 4 4 2 22:21 16
There are teams with same scores, because calculating average of scored and received goals is another way to sort the teams.
First some changes to the Football class:
Override equals to be able to search the list
Override compareTo for sorting
Override toString instead of showTeams
Create a constructor
Combine most functions into teamValues
import java.util.Formatter;
public class Football implements Comparable<Football> {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int score;
private int wins;
private int losses;
private int draws;
private int matchCount;
public int compareTo(Football f) {
return score - f.score;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
else if (o instanceof Football) {
return teamName.equals(((Football)o).teamName);
}
else if (o instanceof String) {
return teamName.equals((String)o);
}
return false;
}
public Football(String teamName) {
this.teamName = teamName;
}
public void teamValues(int scoredGoals, int receivedGoals) {
this.scoredGoals += scoredGoals;
this.receivedGoals += receivedGoals;
matchCount++;
if (scoredGoals < receivedGoals) {
losses++;
}
else if (scoredGoals > receivedGoals) {
wins++;
score += 3;
}
else {
draws++;
score += 1;
}
}
public String toString() {
return new Formatter().format("%-20s %3d %3d %3d %3d %3d:%-3d %d",
teamName, matchCount, wins, draws, losses, scoredGoals, receivedGoals, score)
.toString();
}
}
For the main program, you don't want to create a new team every time - only when a team is first encountered in the file. Put all the teams in a List. When parsing a new game, first try to find the team in the list. If it is not in there, add it.
List<Football> teamsArray = new ArrayList<>();
while (scan.hasNextLine()) {
fileString = scan.nextLine();
String[]match = fileString.split("\\t|:");
if (match.length == 5 && match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
// Create a temp team to search the List
Football team1 = new Football(match[1]);
// Search the list
if (!teamsArray.contains(team1)) {
// Not in the list already. Add it
teamsArray.add(team1);
}
else {
// Already in the List. Use that one.
team1 = teamsArray.get(teamsArray.indexOf(team1));
}
// Repeat for team 2
Football team2 = new Football(match[2]);
if (!teamsArray.contains(team2)) {
teamsArray.add(team2);
}
else {
team2 = teamsArray.get(teamsArray.indexOf(team2));
}
team1.teamValues(team1score, team2score);
team2.teamValues(team2score, team1score);
}
}
System.out.println("Name M W D L S:R S");
// Sort and print
teamsArray
.stream()
.sorted(Comparator.reverseOrder())
.forEach(t -> System.out.println(t));
I'm starting to learn java and I have a problem with my practice exercise.
This is a snippet of the whole code:
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.ArrayList;
import java.sql.PreparedStatement;
private static final int MAX_LINES = 44;
private static final int REPORT_COL1 = 30;
private static final int REPORT_COL = 15;
private ArrayList<String> errors = new ArrayList<String>();
private ArrayList<String> detailReport = new ArrayList<String>();
private ArrayList<String> summaryReport= new ArrayList<String>();
String firstSortCode= (String) parameters.get("01");
if(firstSortCode==null || firstSortCode.trim().equals("")) {
errors.add("Missing required parameter 01");
invalidParameters= true;
}
else {
for(int i=0; i<SORT_CODES.length; i++) {
if(firstSortCode.equals(SORT_CODES[i][0])) {
pSort1 = SORT_CODES[i][1];
sort1Attr = SORT_CODES[i][2];
sort1GetDescTable = SORT_CODES[i][3];
sort1GetDescCode = SORT_CODES[i][4];
sort1GetDescValue = SORT_CODES[i][5];
val1 = firstSortCode + " - " + pSort1;
break;
}
}
if(pSort1.equals("")) {
errors.add("Invalid value '"+ firstSortCode + "' for parameter 01");
invalidParameters= true;
}
}
String mainSelectSQL ="SELECT shrdgmr_pidm, " +
" shrdgmr_levl_code, "+
" shrdgmr_grst_code, "
" NVL("+sort1Attr+", 'Not Reported') ";
mainSelectSQL =mainSelectSQL +
"FROM shrdgmr " +
"WHERE shrdgmr_pidm is not null " +
//Appends the ORDER BY clause
mainSelectSQL+= "ORDER BY "+sort1Attr;
//Executes the query and obtains the ResultSet
ResultSet rs= sqlStatement.executeQuery();
String sort1Desc= "***";
String Sort1Prev= "*";
//Arrays to hold the student counts for each of the reported sort values
int sort1Count= 0;
int grandTotal = 0;
while(rs.next()) {
String Value1 = rs.getString(2);
if(!Value1.equals(prevSort1Value)) {
String sort1Record= Library.lPad(sort1Count, REPORT_COL, ' ');
if(!sort1Desc.equals("***")) {
if(lineCount[0]+4>MAX_LINES) {
startNewPage(detailReport, pageCount, lineCount, currentDate,
databaseName, pGradTerm, pInitiator, sort1Desc, pSort1, false);
}
detailReport.add(Library.rPad(sort1Desc, REPORT_COL1, ' ')+sort1Record);
summaryReport.add(Library.rPad(sort1Desc, REPORT_COL1, ' ')+sort1Record);
lineCount[0]++;
}
//Resets the counter
sort1Count =0;
sort1Desc= getSortDescription(connection, pSort1, sort1GetDescValue, sort1GetDescTable,
sort1GetDescCode, Value1, errors);
}
sort1Count++;
My question is how to merge duplicate items and sum up their count?
For example the code I have now just prints the following in my summary report,
Architecture 40
Engineering 56
Dentistry 66
Architecture 16
Computer Science 10
Engineering 11
Architecture 5
the output should only be:
Architecture 61
Engineering 67
Dentistry 66
Computer Science 10
Architecture 5
I'm just stuck on how I can do this. I'm thinking of using hashmap or hashset but I'm not sure how. Any help is appreciatd, thank u!
If you really dont want to use the aggregate in sql, you can use HashMap<String, Integer>. Something like that:
Map<String, Integer> aggResult = new HashMap<>();
while (rs.next()) {
String name = rs.getString(NAME_INDEX); //NAME_INDEX - name column index
int value = rs.getInt(VALUE_INDEX); //VALUE_INDEX - value column index
aggResult.merge(name, value, Integer::sum);
//if you dont have java8 use this "if":
/*
if (aggResult.containsKey(name)) {
Integer sum = aggResult.get(name);
aggResult.put(name, sum + value);
} else {
aggResult.put(name, value);
}
*/
}
//test output:
aggResult.forEach((key, value) -> System.out.println(key + ": " + value));
Maybe you will need TreeMap (with or without comparator) instead HashMap for order, null-checks on values from ResultSet or something else.
There had to be aggregate functions involved and theres no charm in having a query which says "aggregate without aggregate"
With this below query does the needful. I have used sum because your o/p doesnt look actually like a count data but sum of already counted records
SELECT NAME, SUM(*)
FROM TABLE GROUP BY
NAME
I am having trouble trying to return all the values in my Register class. Currently it only returns BLOGGS, J but should return JONES, F and SINGH, N also. Thank you in advance.
public static String execute(Register reg, Name n) {
reg.removeName(1);
reg.addName(n);
for (Name nm : reg) {
if(nm.getFamilyName().length() >= 5) {
return (nm.getFamilyName().toUpperCase() + ", " + nm.getFirstName().charAt(0) + "\n");
}
return null;
}
}
Here is the test code for the jUnit test
#Test
public void testExecute() {
Register r = new Register();
r.addName(new Name("Joe", "Bloggs"));
r.addName(new Name("Fred", "Jones"));
r.addName(new Name("Nila", "Singh"));
String result = RegisterApp.execute(r, new Name("Cassie", "Downturn"));
String expectedResult = "BLOGGS, J\nSINGH, N\nDOWNTURN, C\n";
assertEquals("The string returned should match the expected result (run 1)", expectedResult, result);
}
As #Carcigenicate already called out, you're returning right away from your for loop.
You could take advantage of stream api here:
public static String execute(Register reg, Name n) {
reg.removeName(1);
reg.addName(n);
return
reg.stream()
.filter(nm -> nm.getFamilyName().length() >= 5)
.map(nm -> nm.getFamilyName().toUpperCase() + ", " + nm.getFirstName().charAt(0) + "\n")
.collect(Collectors.joining());
}
I want to sort the order of the football clubs based on their points. I have created a class that get the values from the internet and process that values to calculate points based on the number of wins, loses and draws. Then I want to write the standings and their data onto a text file in that order. I created 20 different instances for 20 different clubs. However, I don't know what is the best way to sort the order.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CalculateStandings {
private int matches;
private int homeWin;
private int homeDraw;
private int homeLost;
private int homeForGoal;
private int homeAgainstGoal;
private int awayWin;
private int awayDraw;
private int awayLost;
private int awayForGoal;
private int awayAgainstGoal;
private int point;
private int totalWin;
private int totalLost;
private int totalDraw;
private int totalAgainstGoal;
private int totalForGoal;
void getResult(String team_Name) {
try {
URL url = new URL("https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt");
Scanner input = new Scanner(url.openStream());
while (input.hasNext()) {
String mydata = input.nextLine();
if (mydata.contains(team_Name)) {
Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
Matcher matcher = pattern.matcher(mydata);
String result;
if (matcher.find()) {
matches += 1;
result = matcher.group();
if (mydata.startsWith(" " + team_Name)) {
homeForGoal += Integer.parseInt(Character.toString(result.charAt(0)));
homeAgainstGoal += Integer.parseInt(Character.toString(result.charAt(2)));
} else if (mydata.endsWith(" " + team_Name)) {
awayForGoal += Integer.parseInt(Character.toString(result.charAt(2)));
awayAgainstGoal += Integer.parseInt(Character.toString(result.charAt(0)));
}
if (Integer.parseInt(Character.toString(result.charAt(0))) > Integer.parseInt(Character.toString(result.charAt(2)))) {
if (mydata.startsWith(" " + team_Name)) {
point += 3;
homeWin += 1;
} else if (mydata.endsWith(" " + team_Name)) {
awayLost += 1;
}
} else if (Integer.parseInt(Character.toString(result.charAt(0))) < Integer.parseInt(Character.toString(result.charAt(2)))) {
if (mydata.startsWith(" " + team_Name)) {
homeLost += 1;
} else if (mydata.endsWith(" " + team_Name)) {
point += 3;
awayWin += 1;
}
} else {
if (mydata.startsWith(" " + team_Name)) {
point += 1;
homeDraw += 1;
} else if (mydata.endsWith(" " + team_Name)) {
point += 1;
awayDraw += 1;
}
}
}
}
}
totalWin = homeWin + awayWin;
totalLost = homeLost + awayLost;
totalDraw = homeDraw + awayDraw;
totalAgainstGoal = homeAgainstGoal + awayAgainstGoal;
totalForGoal = homeForGoal + awayForGoal;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is my main class:
public class Launcher {
public static void main(String[] args) {
CalculateStandings Arsenal = new CalculateStandings();
CalculateStandings Tottenham = new CalculateStandings();
CalculateStandings WHam = new CalculateStandings();
CalculateStandings CPalace = new CalculateStandings();
CalculateStandings MU = new CalculateStandings();
CalculateStandings MC = new CalculateStandings();
CalculateStandings Everton = new CalculateStandings();
CalculateStandings Liv = new CalculateStandings();
CalculateStandings WBAlbion = new CalculateStandings();
CalculateStandings NU = new CalculateStandings();
CalculateStandings Stoke_City = new CalculateStandings();
CalculateStandings Southampton = new CalculateStandings();
CalculateStandings Leicester_City = new CalculateStandings();
CalculateStandings Bournemouth = new CalculateStandings();
CalculateStandings Watford = new CalculateStandings();
CalculateStandings Brighton = new CalculateStandings();
CalculateStandings Burnley = new CalculateStandings();
CalculateStandings Huddersfield = new CalculateStandings();
CalculateStandings Swansea = new CalculateStandings();
Arsenal.getResult("Arsenal FC");
Tottenham.getResult("Tottenham Hotspur");
WHam.getResult("West Ham United");
CPalace.getResult("Crystal Palace");
MU.getResult("Manchester United");
MC.getResult("Manchester City");
Everton.getResult("Everton FC");
Liv.getResult("Liverpool FC");
WBAlbion.getResult("West Bromwich Albion");
NU.getResult("Newcastle United");
Stoke_City.getResult("Stoke City");
Southampton.getResult("Southampton FC");
Leicester_City.getResult("Leicester City");
Bournemouth.getResult("AFC Bournemouth");
Watford.getResult("Watford FC");
Brighton.getResult("Brighton & Hove Albion");
Burnley.getResult("Burnley FC");
Huddersfield.getResult("Huddersfield Town");
Swansea.getResult("Swansea City");
}
}
I am thinking about storing the values into several arrays using Getter then sort them using sorting algorithm such as Bubble sort. However, as you can see, the number of instances and the number of fields inside each instances are numerous and write them into the arrays manually using Getter would take too much time. Therefore, I would like to ask you if there is a more optimized approach for this.
Use List instead of array. You should also check on the Comparable interface and how to use it. So that later you can use sort method on the List.
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
You can have one single Map with club names as keys and points as values, and you can use lambdas to print out the table, here is an example for sorting clubs based on the points (descending):
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Main {
private static int rank = 1;
public static void main(String[] args) {
Map<String, Integer> teams = new HashMap<>(){{
put("Arsenal", 54);
put("Chelsea", 44);
put("Manchester United", 52);
put("Liverpool", 49);
put("Tottenham", 50);
}};
teams.entrySet().stream()
.sorted((x,y) -> y.getValue().compareTo(x.getValue()))
.forEach(n -> System.out.println(rank++ + ". " + n.getKey() + " with " + n.getValue() + " points."
));
}
}
And the output would be:
Arsenal with 54 points.
Manchester United with 52 points.
Tottenham with 50 points.
Liverpool with 49 points.
Chelsea with 44 points.
If you have any additional questions, just ask me in the comments.
You could use:
ArrayList < CalculateStandings > footballClubs = new ArrayList < CalculateStandings >();
in main class to create array of objects, then use the
void add(footballClubName: CalculateStandings)
method to add the football clubs instances to the arrayList.
-the next step to force the sorting of the objects is to implement the CalculateStandings class to the Comparable interface by editing the head of the class as this
class CalculateStandings implements Comparable < CalculateStandings >
and override the implementation of the compareTo method in the body of class to how to compare between to instance of this class. as this
#Override
public int compareTo(CalculateStandings o) {
if(somthing_field(as_your_calculations) > o.somthing_field)
return 1;
else if (the_something_field < o.something_field)
return -1;
else
return 0;
}
-then by easy in your main class you can just use the java.util.Collections.
sort(arraylist) to sort it in an increasing order as this
java.util.Collections.sort(footballClubs);
then if you want it in a decreasing order u may use the for loop to reverse it.
That's all, but i have a side note on your code, you could shorten it and epitomize reading by using instructors with args instead of this no-arg instructors, and use the club name string as your args and in the implementation of the instructor use your calculations without need to use an instance method,
public CalculateStandings(String footballClubName) {
//put your calculations here and assign the class fields.
}
just use the instructor to instantiate ones and add them to the array like this
footballClubs.add(new CalculateStandings(footballClubName));
I wish it help.
This is the text file
gr.spinellis.ckjm.ClassVisitor 13 2 0 14 74 34 2 9
gr.spinellis.ckjm.ClassMetricsContainer 3 1 0 3 18 0 2 2
gr.spinellis.ckjm.MetricsFilter 7 1 0 6 30 11 2 5
gr.spinellis.ckjm.PrintPlainResults 2 1 0 2 8 0 1 2
gr.spinellis.ckjm.MethodVisitor 11 2 0 21 40 0 1 8
gr.spinellis.ckjm.CkjmOutputHandler 1 1 0 1 1 0 3 1
and this is the code I have written to pars through, I want to skip to one line in between the values, by the way I already skipped the first line by reading one line before entering the while loop .
package javaapplication39;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/* to read CSV file in Java. In this program we will read * list of metrics stored in CSV file as comma separated values. */
public class readallvalues {
public static void main(String... args) {
List<Metrics> metric = readMetricFromCSV("C:\\Users\\hp\\Desktop\\1.txt");
// let's print all the metric read from CSV file
for (Metrics m : metric) {
System.out.println(m);
}
}
private static List<Metrics> readMetricFromCSV(String fileName) {
List<Metrics> metricsss = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
// create an instance of BufferedReader
// using try with resource, Java 7 feature to close resources
try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
br.readLine();
String line1=null;
// read the first line from the text file
String line = br.readLine();
while (line != null) { // loop until all lines are read
String[] attributes = line.split(" "); // the file, using a comma as the delimiter
Metrics valueOfMetric = createMetric(attributes);
metricsss.add(valueOfMetric); // adding metric into ArrayList
//skip empty line
// line.isEmpty() || line.trim().equals("") || line.trim().equals("\n"))
line = br.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return metricsss;
}
private static Metrics createMetric(String[] metadata) {
String name = metadata[0];
int WMC = Integer.parseInt(metadata[1]);
int DIT = Integer.parseInt(metadata[2]);
int NOC = Integer.parseInt(metadata[3]);
int CBO = Integer.parseInt(metadata[4]);
int RFC = Integer.parseInt(metadata[5]);
int LCOM= Integer.parseInt(metadata[6]);
int Ce = Integer.parseInt(metadata[7]);
int NPM = Integer.parseInt(metadata[8]);
return new Metrics(name,WMC,DIT,NOC,CBO,RFC,LCOM,Ce,NPM);//,cc
}
}
class Metrics {
private String name;
private int WMC;
private int DIT;
private int NOC;
private int CBO;
private int RFC;
private int LCOM;
private int Ce;
private int NPM;
public Metrics( String name,int WMC,int DIT,int NOC,int CBO,int RFC,int LCOM, int Ce, int NPM) {
this.name = name;
this. WMC =WMC ;
this. DIT =DIT ;
this. NOC = NOC;
this. CBO =CBO ;
this. RFC = RFC;
this.LCOM = LCOM;
this.Ce =Ce ;
this. NPM = NPM;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getWMC() { return WMC ; }
public void setWMC(int WMC) { this.WMC = WMC ; }
//WMC, DIT, NOC, CBO, RFC,LCOM, Ca, Ce, NPM,LCOM3,LOC, DAM, MOA, MFA, CAM,IC, CBM and AMC ,cc
public int getDIT() { return DIT ; }
public void setDIT(int DIT) { this.DIT = DIT ; }
public int getNOCC() { return NOC ; }
public void setNOC(int NOC) { this.NOC = NOC ; }
public int getCBO() { return CBO ; }
public void setCBO(int CBO) { this.CBO = CBO ; }
public int getRFC() { return RFC ; }
public void setRFC(int RFC) { this.RFC = RFC ; }
public int getLCOM() { return LCOM ; }
public void setLCOM(int LCOM) { this.LCOM = LCOM ; }
public int getCe() { return Ce ; }
public void setCe(int Ce) { this.Ce = Ce ; }
public int getNPM() { return NPM ; }
public void setNPM(int NPM) { this.NPM = NPM ; }
#Override
public String toString() {
return "name= " + name +" WMC= " + WMC + " DIT= " + DIT + " NOC " + NOC + " CBO " + CBO
+ " RFC " + RFC + " LCOM " + LCOM + " Ce " + Ce + " NPM " + NPM +"\n\n" ;//+ " cc " + cc
}
}
You are reading br.readLine(); outside the loop, just below the try with resource declaration, which skips the very first line.
Add br.readLine() call at the end of while loop, to skip empty line. Problem with this is it will also skip line with text if your file has two consecutive empty lines instead of one.
while ((line = br.readLine()) != null) {
//..logic
br.readLine();//add call to skip this line
}
You should better check whether line is empty or not to perform your logic.
while ((line = br.readLine()) != null) {
//trim will remove leading and trailing white space characters
if(!"".equals(line.trim()) {
//..logic
}
}
Apart from that you should follow naming convention, class name should start with capital case. So, your class name should be ReadAllvalues.