Elements from a text file not being added to the array - java

I'm trying to add an Entry object to an array of Entries which consists of a Surname, Initial and Extention number. The first word on the line is the surname etc. however when I print the array using System.out.print(Arrays.toString(entries)); it doesn't print the array or it is empty.
Entry class
public class Entry {
private String surname, initial, extension;
public Entry() {
}
// shadowing
public Entry(String line) {
String[] lines = line.split("\t");
this.surname = lines[0];
this.initial = lines[1];
this.extension = lines[2];
}
public void setSurname(String sur) {
this.surname = sur;
}
public void setInitial(String ini) {
this.initial = ini;
}
public void setExtention(String ext) {
this.extension = ext;
}
public String getSurname() {
return surname;
}
public String getInitial() {
return initial;
}
public String getExtension() {
return extension;
}
}
Array directory class
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayDirectory implements Directory {
Entry[] entries = new Entry[0];
int lines = 0;
public ArrayDirectory() {
try {
Scanner inFile = new Scanner(new FileReader("directory.txt"));
Scanner lCounter = new Scanner(new FileReader("directory.txt"));
while (lCounter.hasNext()) {
lCounter.nextLine();
lines++;
}
entries = new Entry[lines];
for(int i = 0; i < lines; i++){
addEntry(inFile.nextLine());
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void addEntry(String l) {
Entry newEntry = new Entry(l);
int i = 0;
while(entries[i] != null) i++;
}
public void printTable(){
System.out.print(Arrays.toString(entries));
}
}

You are not adding anything to your array:
public void addEntry(String l) {
Entry newEntry = new Entry(l);
int i = 0;
while(entries[i] != null) i++;
}
You are missing an eventual entries[i] = newEntry;. Of course, once your array is full you'll get an exception with this code. You must ensure i doesn't grow larger than entries.size -1.
Consider using a list instead of an array.

Your Entry class need to override the toString() method. It is this method that Arrays.toString() will use and unless you implement your own version it will fall back to the default one from java.lang.Object which is not very human friendly.
#Override
public String toString() {
return String.format("%s. %s", this.initial, this.surname);
}
You might be better off using a more flexible storage type too so you do not have to read through the file twice. An ArrayList would be appropriate and you can convert it to an array trivially after you have finished adding new entries to it.
How big is your file? Maybe a BufferedReader would be a better choice?
File file = new File("directory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<Entry> entries = new ArrayList<Entry>()
while ((line = br.readLine()) != null) {
entries.add(new Entry(line));
}
br.close();
Edit: You are not actually adding your Entry objects to the array. You should change this section:
entries = new Entry[lines];
for(int i = 0; i < lines; i++){
addEntry(inFile.nextLine());
}
and this method:
public void addEntry(String l) {
Entry newEntry = new Entry(l);
int i = 0;
while(entries[i] != null) i++;
}
You could add entries[i] = newEntry; just after that final while loop but it is a very poor way to do it. You are iterating through the whole array every time you add a new item. I'd suggest the ArrayList method I describe above.

Related

Parse a text file, split it into lines, return a list and map into objects

So I have have 2 types of files, one for level definition and other for blocks structure definition.
I need to parse both of them into list of strings which contains the lines, and go over the list and over each line, split and parse and map them into java objects.
I have no lead how to do it, I have read about java io reader but I do get confused here where and how to use it.
Understanding the content of the level specification of a single level: this will go over the strings, split and parse them, and map them to java objects, resulting in a LevelInformation object.
P.S I already wrote and built the LevelInformation interface(which works if I manually write a level that implements this interface), which contains every thing that is in the text file (level name, velocities,background and etc..)
So basically I just need to parse those texts file and map them into this interface.
public interface LevelInformation {
int numberOfBalls();
// The initial velocity of each ball
// Note that initialBallVelocities().size() == numberOfBalls()
// velocities created by (a,s) format. a = angle, s = speed.
List<Velocity> initialBallVelocities();
int paddleSpeed();
int paddleWidth();
// the level name will be displayed at the top of the screen.
String levelName();
// Returns a sprite with the background of the level
Sprite getBackground();
// The Blocks that make up this level, each block contains
// its size, color and location.
List<Block> blocks();
// Number of blocks that should be removed
// before the level is considered to be "cleared".
// This number should be <= blocks.size();
int numberOfBlocksToRemove();
}
An example of the files:
level_definition.txt
START_LEVEL
level_name:Square Moon
ball_velocities:45,500
background:image(background_images/night.jpg)
paddle_speed:650
paddle_width:160
block_definitions:definitions/moon_block_definitions.txt
blocks_start_x:25
blocks_start_y:80
row_height:100
num_blocks:4
START_BLOCKS
--ll--
--ll--
END_BLOCKS
END_LEVEL
block_definitions.txt
#block definitions
bdef symbol:l width:100 height:100 fill:color(RGB(154,157,84))
#spacers definitions
sdef symbol:- width:30
So I need to create a list and get a reader and somehow parse it.
I'll be glad to get some tips, ideas and help for doing this.
Thanks.
public class LevelSpecificationReader {
public List<LevelInformation> fromReader(java.io.Reader reader) {
// ...
}
}
I think I need to:
Split the file into lines and make a list of strings out of them.
Which means each line will get into the list as a string.
Get each line, and also split it into I don't know what, but in order
to get info and map in into the needed object. For example:
level_name: something
i'll have to get "something" into "level name" in my interface.
This is my failed attempt:
public List<LevelInformation> fromReader(java.io.Reader reader) throws IOException {
ArrayList<String> listOfLines = new ArrayList<>();
BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
String line = bufReader.readLine();
while (line != null) {
listOfLines.add(line);
line = bufReader.readLine();
}
return listOfLines;
}
This code brings an error bcause I return a list of string but I need a list of LevelInformation.
This is not a complete solution, since the code in your question is not a reproducible example since it is not complete. Where are the definitions of classes Block and Sprite and Velocity? Well I guessed those and made up minimal definitions for them.
My hope is that the below code will be enough to help you complete your project. It is based on the details you posted including the sample file: level_definition.txt
Class Sprite
import java.awt.Image;
public class Sprite {
private Image image;
public Sprite(Image image) {
this.image = image;
}
}
class Velocity
public class Velocity {
private int speed;
public Velocity(int speed) {
this.speed = speed;
}
}
Class LevelDtl which implements your interface: LevelInformation.
Personally, I don't see the need for an interface. I think it should be a class.
public class LevelDtl implements LevelInformation {
private String levelName;
private List<Velocity> ballVelocities;
private Sprite background;
private int paddleSpeed;
private int paddleWidth;
private List<Block> blocks;
private int numBlocks;
#Override
public int numberOfBalls() {
return ballVelocities == null ? 0 : ballVelocities.size();
}
#Override
public List<Velocity> initialBallVelocities() {
return ballVelocities;
}
#Override
public int paddleSpeed() {
return paddleSpeed;
}
#Override
public int paddleWidth() {
return paddleWidth;
}
#Override
public String levelName() {
return levelName;
}
#Override
public Sprite getBackground() {
return background;
}
#Override
public List<Block> blocks() {
return blocks;
}
#Override
public int numberOfBlocksToRemove() {
return numBlocks;
}
public void setBackground(Sprite bg) {
background = bg;
}
public void setBallVelocities(List<Velocity> velocities) {
ballVelocities = velocities;
}
public void setLevelName(String name) {
levelName = name;
}
public void setPaddleSpeed(int speed) {
paddleSpeed = speed;
}
public void setPaddleWidth(int width) {
paddleWidth = width;
}
public String toString() {
return String.format("Level: %s , Paddle: [speed = %d , width = %d]",
levelName,
paddleSpeed,
paddleWidth);
}
}
All the methods with #Override annotation are implementations of methods in LevelInformation interface. Also, note that method toString() is only for debugging purposes since I use it in the final class which is the one you named: LevelSpecificationReader. It reads the file level_definition.txt line by line, assuming the format shown in your question and builds and configures an instance of class LevelDtl which it then adds to a List. Finally, the below code prints the contents of the List. Of-course, using the sample data you provided in your question, the List contains only one element.
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.imageio.ImageIO;
public class LevelSpecificationReader {
private static final String BACKGROUND = "background:";
private static final String BALL_VELOCITIES = "ball_velocities:";
private static final String END_BLOCKS = "END_BLOCKS";
private static final String END_LEVEL = "END_LEVEL";
private static final String IMAGE = "image(";
private static final String LEVEL_NAME = "level_name:";
private static final String PADDLE_SPEED = "paddle_speed:";
private static final String PADDLE_WIDTH = "paddle_width:";
private static final String START_BLOCKS = "START_BLOCKS";
private static final String START_LEVEL = "START_LEVEL";
private static void setBackground(LevelDtl level, String data) throws IOException {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
// image(background_images/night.jpg)
if (data.startsWith(IMAGE)) {
String path = data.substring(IMAGE.length(), data.length() - 1);
BufferedImage image = ImageIO.read(new File(path));
level.setBackground(new Sprite(image));
}
}
}
private static void setInitialBallVelocities(LevelDtl level, String data) {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
String[] numbers = data.split(",");
if (numbers.length > 0) {
List<Velocity> velocities = new ArrayList<>();
for (String number : numbers) {
try {
int speed = Integer.parseInt(number);
Velocity velocity = new Velocity(speed);
velocities.add(velocity);
}
catch (NumberFormatException xNUmberFormat) {
// Ignore.
}
}
level.setBallVelocities(velocities);
}
}
}
private static void setPaddleSpeed(LevelDtl level, String data) {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
int speed;
try {
speed = Integer.parseInt(data);
}
catch (NumberFormatException xNumberFormat) {
speed = 0;
}
level.setPaddleSpeed(speed);
}
}
private static void setPaddleWidth(LevelDtl level, String data) {
Objects.requireNonNull(level, "Null level.");
if (data != null && !data.isEmpty()) {
int width;
try {
width = Integer.parseInt(data);
}
catch (NumberFormatException xNumberFormat) {
width = 0;
}
level.setPaddleWidth(width);
}
}
/**
* Start here.
*/
public static void main(String[] args) {
try (FileReader fr = new FileReader("level_definition.txt");
BufferedReader br = new BufferedReader(fr)) {
List<LevelInformation> levels = new ArrayList<>();
LevelDtl level = null;
String line = br.readLine();
while (line != null) {
if (START_LEVEL.equals(line)) {
// End current level.
if (level != null) {
levels.add(level);
}
// Start next level.
level = new LevelDtl();
}
else if (line.startsWith(LEVEL_NAME)) {
level.setLevelName(line.substring(LEVEL_NAME.length()));
}
else if (line.startsWith(BALL_VELOCITIES)) {
setInitialBallVelocities(level, line.substring(BALL_VELOCITIES.length()));
}
else if (line.startsWith(BACKGROUND)) {
setBackground(level, line.substring(BACKGROUND.length()));
}
else if (line.startsWith(PADDLE_SPEED)) {
setPaddleSpeed(level, line.substring(PADDLE_SPEED.length()));
}
else if (line.startsWith(PADDLE_WIDTH)) {
setPaddleWidth(level, line.substring(PADDLE_WIDTH.length()));
}
line = br.readLine();
}
if (level != null) {
levels.add(level);
}
System.out.println(levels);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
The above code only handles lines in file level_definition.txt up to and including this line:
paddle_width:160
Good luck with adding code to handle the rest of the contents of the file.
Maybe what you want is to break it into pieces first so that you don't need to worry about all the things at once and focus on parsing the strings. All you need to do is make a constructor that accepts string and then parse it in the constructor
public List<LevelInformation> fromReader(java.io.Reader reader) throws IOException {
ArrayList<LevelInformation> listOfLines = new ArrayList<>();
BufferedReader bufReader = new BufferedReader(new FileReader("file.txt"));
String line = bufReader.readLine();
while (line != null) {
listOfLines.add(new LevelInformation(line));
line = bufReader.readLine();
}
return listOfLines;
}
public class LevelInformation {
LevelInformation (String text) {
parseText(text);
}
private void parseText(String text) {
//do something here
}
}

Array outputs random sequence of characters instead of desired result

I am attempting to write a program that will output data received from a csv file. The CSV file is composed of 28 or so strings/lines with each data in the line separated by a comma into 5 categories (Team name, League, Coaches, Division and Full Time).
I actually have a couple of issues...
When i run my program, i receive a random sequence of characters (such as: [Ljava.lang.String;#5e34d46a) in my coaches category instead of a name that i am expecting. Does this have something to do with it being in an array? How would i solve it.
The categories for each string are displayed in the output as a list, i would like to output the data of strings into a line. For example, instead of the output displaying:
Team name: Team A
League: Western Conference
Coaches: [Ljava.lang.String;#1c751d58
Division: 2
Full Time: true
I would like it to be displayed as a line.
The last category of a single instance of a string in the output is attached to the first category of the next string. Like so: Full Time: trueTeam name: Team A. How would i separate this?
My Team.java code:
public class Team
{
private String name;
private String league;
private String[] coaches;
private String division;
private boolean fullTime;
public Team(String dataLine)
{
String[] data = dataLine.split(",");
this.name = data[0];
this.coaches = getStringAsArray(data[1], ":");
this.league = data[2];
this.division = data[3];
this.fullTime = data[4].equals("yes");
}
public Team(){
}
private String[] getStringAsArray(String t, String delimiter)
{
String[] result = t.split(delimiter);
return result;
}
private String getArrayAsString(String[] coaches)
{
coaches = this.getCoaches();
String result = "";
for(int i = 0; i<coaches.length; i++)
{
result += coaches[i] +" ";
}
result = result.trim();
return result;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setCoaches(String coaches)
{
this.coaches = getStringAsArray(coaches, ":");
}
public String getCoachesAsString()
{
String result = getArrayAsString(coaches);
return result;
}
public boolean isFullTime() {
return fullTime;
}
public void setFullTime(boolean fullTime) {
this.fullTime = fullTime;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String[] getCoaches() {
return coaches;
}
public void setCoaches(String[] coaches) {
this.coaches = coaches;
}
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#Override
public String toString() {
return "Team name: " + name + "\nLeague: " + this.league + "\nCoaches: " + this.coaches + "\nDivision: " + this.division + "\nFull Time: " + this.fullTime;
}
}
My StoreData.java code:
import shiftershape.model.Team;
import java.util.ArrayList;
public class StoreData {
public static ArrayList<Team> teams = new ArrayList<Team>();
public static String getTeams()
{
String s = "";
for(int i = 0; i < teams.size(); i++){
s += teams.get(i);
}
return s;
}
public static ArrayList<Team> TeamListFromArray(String[] as)
{
ArrayList<Team> teams = new ArrayList<Team>();
// for( int i= 0 ; i < as.length; i++){
for (String s: as){
teams.add(new Team(s));
}
return teams;
}
}
My ReadCSV.java code:
import Utilities.StoreData;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import shiftershape.model.Team;
public class ReadCsv {
public void readCsv() {
String csvFileToRead = "C:/Users/Fryyy/Desktop/FootballRepo/TestData/football_teams_phase1.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
int i = 0;
while ((line = br.readLine()) != null) {
Team one = new Team(line);
if(i > 0){
StoreData.teams.add(new Team(line));
}else{
i++;
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static ArrayList<Team> getTeams() {
return StoreData.teams;
}
public static void setTeams(ArrayList<Team> teams) {
StoreData.teams = teams;
}
}
My FootballC.java code:
import Utilities.StoreData;
import shiftershape.model.Team;
public class FootballC {
public static void main(String[] args)
{
ReadCsv junk = new ReadCsv();
junk.readCsv();
System.out.println(StoreData.getTeams());
}
}
System.out.println(StoreData.getTeams()); will call toString() on String[]
try this:
for (String s : StoreData.getTeams()) {
System.out.println(s);
}
[Ljava.lang.String;#5e34d46a) is the resource code for an object when printed to standard out. In this case being a string, so somewhere it looks like you're printing an array instead of the value within the array, causing the resource ID to be shown instead of the values within, as Java doesn't print array contents by default.
[Ljava.lang.String;#1c751d58 is the String version of an array. Arrays don't have a nice toString() method. If you used Lists in stead of Arrays it will print better.
The quick conversion of an array to a list is Arrays.asList(array);

Not sure how to create a default constructor

I'm having trouble creating a parameterless default constructor for this class I am writing. The constructor should go into:
public Track(){
}
The following code is the entire class I'm working on, I've tried using the returned values from the below methods and setting them to 0 but that doesn't seem to work. Any help would be greatly appreciated.
package comp125;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Track {
//removed max entries (was 1000, now has no limit)
ArrayList<Waypoint> pointList = new ArrayList<Waypoint>();{
//for (int i = 0; i < pointList.size(); i++){
//System.out.println(pointList.get(i));
//}
}
Scanner scanner;
String fileMain;
public Track(String filename) throws IOException, GPSException {
Scanner scanner = new Scanner(new FileReader(filename));
scanner.hasNextLine();
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
pointList.add(new Waypoint(line));
}
File f = new File(filename); //easy filenotfound exception
if(!f.exists()){
throw new IOException();
}
fileMain = filename;
}
//This is where we create an empty track
public Track(){
}
public int size() {
return pointList.size();
}
public void add(Waypoint wp) {
pointList.add(pointList.size(), wp);
}
public String getFilename() {
return fileMain;
}
public String getTimestamp() {
return pointList.get(0).getTimestamp();
}
public double getDistance() {
double totDist = 0.0;
for (int i = 1; i < pointList.size(); i++)
{
totDist = totDist + pointList.get(i-1).distanceTo(pointList.get(i));
}
//System.out.println(totDist);
return totDist;
}
public double getElevationGain() {
double elevGain = 0.0;
for(int i = 1; i < pointList.size(); i++){
if(pointList.get(i).getElevation() > pointList.get(i-1).getElevation() ){
elevGain = elevGain + Math.abs(pointList.get(i).getElevation() - pointList.get(i-1).getElevation());
}
}
return elevGain;
}
public String toString() {
String str1 = this.getFilename();
String str2 = this.getTimestamp();
String str3 = String.valueOf(this.getDistance());
String str4 = String.valueOf(this.getElevationGain());
//System.out.println(str1);
//System.out.println(str2);
//System.out.println(str3);
return str1 + str2 + str3 + str4;
}
public Waypoint closestTo(Waypoint wp) {
Waypoint returnValue = pointList.get(0);
for(int i = 1; i < pointList.size(); i++){
if(pointList.get(i).distanceTo(wp) < returnValue.distanceTo(wp)){
returnValue = pointList.get(i);
}
}
return returnValue;
}
}
If you are asking what to put into the parameter-less constructor, you have two options :
Keep it empty - all the properties will be initialized to their default values
public Track()
{
}
Use some default value instead of filename, and use it to initialize the instance the same way you do in your other constructor Track(String filename). You can even call one constructor from the other :
public Track() throws IOException, GPSException
{
this("DEFAULT_FILE_NAME");
}
If you require a parameter-less constructor throwing no exceptions, you can catch the exceptions thrown from the other constructor.
I think what is happening is you're attempting to use the class, but there is no data.
You can create fake (mock) data like so:
public Track(){
for (int i = 0; i < 10; i++){
pointList.add(new Waypoint(/* put the data here that you need for the Waypoint constructor */);
}
}
But your comment //This is where we create an empty track on the constructor seems appropriate...there aren't any tracks =)

sort two columns in a text file by using java collections framework

I have an input file containing lines like
21,mahesh
12,suresh
23,rajesh
25,lokesh
By using ArrayList I wrote code the code below to handle ascending and descending order
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class FileRead {
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(new FileReader("D:\\Numbers.txt"));
ArrayList<String> al = new ArrayList<String>();
while (s.hasNextLine()) {
String line = s.nextLine();
al.add(line);
}
Collections.sort(al,Collections.reverseOrder());
for (String i: al)
System.out.println(i);
}
}
This yielded the following output
- 25,lokesh
- 23,rajesh
- 21,mahesh
- 12,suresh
$ In the above code, when I take the entire row as a line by using Collections.sort() operation it works.
$ If I take the input like below String column first and integer column next the above code is not working properly it will assign by using String values Alphabetical order,i want to sort the data by using only integer not by String values please help me friends
- mahesh,21
- suresh,12
- rajesh,23
- lokesh,25
First Read the file store it in a Map
Map map = new TreeMap();
while(true)
{
String line = bufferedReader.readLine();
if(line == null)
break;
else {
String arr[] = line.split(",");
for(int i=0;i<arr.length-1;i++)
{
map.put(arr[i],arr[i+1]);
}}
}
Sort it using Comparator
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
Finally displat the result
Map result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());
For acending switch o1 and o2 in when returning from comparator.
For the second type of input
List list = new LinkedList(map.keySet());
Collections.sort(list);
Set set = map.entrySet();
Map result = new LinkedHashMap();
for (Iterator it = set.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());
The following will allow you to parse the information into the appropriate types using a class LineEntry to wrap the data. It will provide the proper sorting on Integer values instead of treating them as Strings and applying alphabetical ordering.
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class FileRead {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(new InputStreamReader(FileRead.class.getResourceAsStream("/numbers.txt")));
s.useDelimiter("[,\\s]");
ArrayList<LineEntry> lineEntryList = new ArrayList<LineEntry>();
while (s.hasNextLine()) {
int amount = s.nextInt();
String value = s.next();
LineEntry lineEntry = new LineEntry(value, amount);
lineEntryList.add(lineEntry);
}
Collections.sort(lineEntryList, Collections.reverseOrder());
for (LineEntry i : lineEntryList) {
System.out.println(i);
}
}
public static class LineEntry implements Comparable<LineEntry>{
private String value;
private Integer amount;
public LineEntry(String value, Integer amount) {
this.value = value;
this.amount = amount;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
#Override
public String toString() {
return "LineEntry{" + "value=" + value + ", amount=" + amount + '}';
}
#Override
public int compareTo(LineEntry o) {
int compareTo = o.getAmount().compareTo(amount);
if (compareTo == 0) {
compareTo = o.getValue().compareTo(value);
}
return compareTo;
}
}
Better to create a different class which contains data in each line seperated by comma as variables of that class so that in future if you have multiple columns data in the same line then the code can be scalable and also you can create custom comparators based on your sort condition:-
public class FileRead {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(new FileReader("E:\\Numbers.txt"));
List<FileObject> al = new ArrayList<FileObject>();
while (s.hasNextLine()) {
String line = s.nextLine();
al.add(new FileObject().createFileObject(line));
}
Collections.sort(al,new FileObjectComparator());
for (FileObject i: al)
System.out.println(i);
}
}
class FileObject {
private int id;
private String name;
public FileObject createFileObject(String line) {
if(line != null && !line.isEmpty()) {
for(String str : line.split(",")) {
str = str.trim();
if(str.matches("([\\d]*)")) {
id = Integer.valueOf(str);
} else {
name = str;
}
}
}
return this;
}
... // getters and setters
#Override
public String toString() {
return "[ID] "+id+ " [Name] "+name ;
}
}
class FileObjectComparator implements Comparator<FileObject> {
#Override
public int compare(FileObject o1, FileObject o2) {
return o2.getId() - o1.getId();
}
}

Java Question Linked List objects

I have the following piece of code :
Essentially the number of methods should remain the same as in the code and I need to extract a string from an element of the linkedlist of Objects of type emp_struct.. How do I do it?
import java.util.*;
import java.io.*;
class a1 {
static LinkedList l1;
private emp_struct input() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
emp_struct obj = new emp_struct();
obj.emp_id = br.readLine();
obj.name = br.readLine();
obj.salary = Double.parseDouble(br.readLine());
obj.dept = br.readLine();
try{
search(obj);
}catch(Exception e){
System.out.println(e);
obj = input();
}
return obj;
}
boolean search(emp_struct obj)
{
int lastIndex = l1.lastIndexOf(l1);
int begIndex = 0;
for(begIndex =0;begIndex<lastIndex;begIndex++)
{
Object chkCase = l1.get(begIndex);
String chk = chkCase.getEmpID();
if(chk.equals(obj.emp_id));
throw new DuplicateEntryException("Duplicate entry found");
}
return true;
}
public static void main(String args[]) throws IOException
{
l1 = new LinkedList();
}
}
class DuplicateEntryException extends Exception {
String detail;
DuplicateEntryException(String a)
{
detail = a;
}
public String toString()
{
return "User Defined Exception : "+detail;
}
}
class emp_struct {
public String emp_id;
public String name;
public double salary;
public String dept;
public String getEmpID()
{
return emp_id;
}
public String toString()
{
return emp_id+"\t"+name+"\t"+salary+"\t"+dept;
}
}
In your search method, if you find the value, you're throwing an exception. If you don't find the value, you return true. This doesn't seem like the best approach.
If you find the value, shouldn't you return true, then if it makes it through the array without finding it, shouldn't you return false?
This line
Object chkCase = l1.get(begIndex);
should be
emp_struct chkCase = (emp_struct)l1.get(begIndex);
among other things...

Categories

Resources