Here is the list function, as you can see it's printing the content of newEntry before being added to the vector dataList.
public static Vector<entry> list()
{
entry newEntry = new entry();
Vector<entry> dataList = new Vector<entry>();
String[] splitLine;
String currentLine;
String formattedString = "";
BufferedReader in;
try
{
in = new BufferedReader(new FileReader(new File("data.txt")));
while ((currentLine = in.readLine()) != null) {
newEntry = new entry();
splitLine = currentLine.split(" ");
newEntry.record = Integer.parseInt(splitLine[0]);
newEntry.fName = splitLine[1];
newEntry.lName = splitLine[2];
newEntry.phoneNumber = splitLine[3];
dataList.add(newEntry);
}
}
catch (IOException ex)
{
System.out.println(ex);
}
for (int i = 0; i < dataList.size(); i++)
{
System.out.println(dataList.elementAt(i).record + dataList.elementAt(i).fName + dataList.elementAt(i).lName + dataList.elementAt(i).phoneNumber);
}
return dataList;
}
Here is the part where I'm having an issue, it's taking whatever list() is returned (above) and forming it into a new vector and will be printed off. However, it's only printing the last value for some reason...
if ((params[0].toLowerCase()).equals("list"))
{
Vector<entry> printList = new Vector<entry>(list());
for (int i = 0; i < printList.size(); i++)
{
System.out.println(printList.elementAt(i).record + printList.elementAt(i).fName + printList.elementAt(i).lName + printList.elementAt(i).phoneNumber);
}
}
This is the output I get when 3 (the first 3 shown below) is added to the dataList in the list function.
1000 John Carter 1731371313
1001 Abe Lincoln 9173913143
1002 William Tell 794174141
1002 William Tell 794174141
1002 William Tell 794174141
1002 William Tell 794174141
Does anyone know what may be wrong?
That's because you insert the same object into the container three times. You should construct a new object before inserting it.
splitLine = currentLine.split(" ");
newEntry = new entry();
newEntry.record = Integer.parseInt(splitLine[0]);
newEntry.fName = splitLine[1];
newEntry.lName = splitLine[2];
newEntry.phoneNumber = splitLine[3];
System.out.println(newEntry.record + newEntry.fName + newEntry.lName + newEntry.phoneNumber);
dataList.add(newEntry);
It's a good thing you posted your full code, because you have an additional error :
public static class entry
{
public static int record;
public static String fName;
public static String lName;
public static String phoneNumber;
}
Declaring the members of the entry class as static causes them to be shared by all instances of your class. That's why all instances of the entry class hold the values of the last entry. Remove the static keyword from all the members and everything will work.
You keep overwriting newEntry.
This line needs to be in the loop:
entry newEntry = new entry();
entry newEntry = new entry();
This is the only place where you declare an entry object. As such, when you do this:
newEntry.record = Integer.parseInt(splitLine[0]);
newEntry.fName = splitLine[1];
newEntry.lName = splitLine[2];
newEntry.phoneNumber = splitLine[3];
You're just changing the values in the current object.
A better approach might look like this:
while ((currentLine = in.readLine()) != null) {
newEntry = new entry();
splitLine = currentLine.split(" ");
newEntry.record = Integer.parseInt(splitLine[0]);
newEntry.fName = splitLine[1];
newEntry.lName = splitLine[2];
newEntry.phoneNumber = splitLine[3];
dataList.add(newEntry);
}
But if I were doing it, I'd write a constructor for the entry class that just takes 4 strings, and initializes record, fName, lName, and phoneNumber based on these 4 strings (you can parseInt within the constructor).
For example:
public entry(string rec, string first, string last, string phone) {
record = Integer.parseInt(rec);
fName = first;
lName = last;
phoneNumber = phone;
}
So then in your loop where you're taking the data in, you can simply do this:
while ((currentLine = in.readLine()) != null) {
splitLine = currentLine.split(" ");
newEntry = new entry(splitLine[0], splitLine[1], splitLine[2], splitLine[3]);
dataList.add(newEntry);
}
Its because you are using the same instance of entry in your while. You are making the instance before your while. Each file's row in your code is one entry, right? So, making a new inatance for each line.
while ((currentLine = in.readLine()) != null){
newEntry = new entry();
//do whatever you want
dataList.add(newEntry);
}
Related
I'm trying to import a txt file with car info and separate the strings into arrays and then display them. The number of doors is combined with the next number plate. Have tried a few ways to get rid of the whitespace characters which I think is causing the issue but have had no luck.
whitespace chars
My code displays this result:
Number Plate : AG53DBO
Car Type : Mercedes
Engine Size : 1000
Colour : (255:0:0)
No. of Doors : 4
MD17WBW
Number Plate : 4
MD17WBW
Car Type : Volkswagen
Engine Size : 2300
Colour : (0:0:255)
No. of Doors : 5
ED03HSH
Code:
public class Application {
public static void main(String[] args) throws IOException {
///// ---- Import File ---- /////
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
String content = stringBuilder.toString();
///// ---- Split file into array ---- /////
String[] dataList = content.split(",");
// Display array
for (String temp : dataList) {
// System.out.println(temp);
}
ArrayList<Car> carArray = new ArrayList();
// Loop variables
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 5) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
}
}
And
public class Car {
String[] data;
private String modelUnpro;
private String engineSizeUnpro;
private String registrationUnpro;
private String colourUnpro;
private String doorNoUnpro;
// Constructor
public Car(String[] data, int arrayPosition) {
registrationUnpro = data[arrayPosition];
modelUnpro = data[arrayPosition + 1];
engineSizeUnpro = data[arrayPosition + 2];
colourUnpro = data[arrayPosition + 3];
doorNoUnpro = data[arrayPosition + 4];
}
// Getters
private String getModelUnpro() {
return modelUnpro;
}
private String getEngineSizeUnpro() {
return engineSizeUnpro;
}
private String getRegistrationUnpro() {
return registrationUnpro;
}
private String getColourUnpro() {
return colourUnpro;
}
private String getDoorNoUnpro() {
return doorNoUnpro;
}
public String displayCar() {
return "Number Plate : " + getRegistrationUnpro() + "\n Car Type : " + getModelUnpro() + "\n Engine Size : "
+ getEngineSizeUnpro() + "\n Colour : " + getColourUnpro() + "\n No. of Doors : " + getDoorNoUnpro() + "\n";
}
}
Text file:
AG53DBO,Mercedes,1000,(255:0:0),4
MD17WBW,Volkswagen,2300,(0:0:255),5
ED03HSH,Toyota,2000,(0:0:255),4
OH01AYO,Honda,1300,(0:255:0),3
WE07CND,Nissan,2000,(0:255:0),3
NF02FMC,Mercedes,1200,(0:0:255),5
PM16DNO,Volkswagen,1300,(255:0:0),5
MA53OKB,Honda,1400,(0:0:0),4
VV64BHH,Honda,1600,(0:0:255),5
ER53EVW,Ford,2000,(0:0:255),3
Remove Line separator from while loop.
String fileName = "D:\\Files\\a.txt";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line.trim());
}
reader.close();
String content = stringBuilder.toString();
String[] dataList = content.split(",");
ArrayList<Car> carArray = new ArrayList();
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 3) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
In StringBuilder you collect all lines:
AG53DBO,Mercedes,1000,(255:0:0),4\r\nMD17WBW,Volkswagen,2300,(0:0:255),5\r\n...
This string should first be spit on ls - and then you have lines with fields separated by comma.
Now just splitting by comma will cause a doubled array element 4\r\nMD17WBW.
Something like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path); // Without line ending.
List<Car> cars = new ArrayList<>();
for (String line : lines) {
String[] data = line.split(",");
Car car = new Car(data);
cars.add(car);
}
Path, Paths and especially Files are very handy classes. With java Streams one also can abbreviate things like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<Car> cars = Files.lines(path) // Stream<String>
.map(line -> line.split(",")) // Stream<String[]>
.map(Car::new) // Stream<Car>
.collect(Collectors.toList()); // List<Car>
Here .lines returns a Stream<String> (walking cursor) of lines in the file, without line separator.
Then .map(l -> l.split(",")) splits every line.
Then the Car(String[]) constructor is called on the string array.
Then the result is collected in a List.
I know there are other solutions out there but nothing is working for me.
Question: In my main method, I group together IDs by rating and make the rating the key and the rest of the info the value as a List. When I create the hashmap and put in the lists I can accurately print the contents of the hashmap. However, once I pass the map the evaluate method, the values are lost and I cannot iterate in the same way that I did in the main method, even though the logic is the same. I am not experienced with the Map class in java. Can somebody please help me figure out why when I pass the Map to my evaluate method that I can no longer iterate the Map?
import java.io.*;
import java.util.*;
public class Evaluate {
public static double grandTotal;
public static void main(String[] args) throws Exception {
FileInputStream fs = new FileInputStream("testInput.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileInputStream fs2 = new FileInputStream("testTest.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));
String line;
String line2;
String[] bloop;
String bleep;
String flooper;
String splitter;
String[] splitInput;
List<String> oneStarList= new ArrayList<String>();
List<String> twoStarList= new ArrayList<String>();
List<String> threeStarList= new ArrayList<String>();
List<String> fourStarList= new ArrayList<String>();
List<String> fiveStarList= new ArrayList<String>();
List<String> values2 = new ArrayList<String>();
try {
while ((line=br.readLine()) != null) {
bloop = new String[10];
bloop = line.split("\\s+");
bleep = bloop[1].toString();
flooper = (bloop[0]+" "+bloop[2]+" "+bloop[3]+" "+bloop[4]);
if (bleep.equals("1")){
oneStarList.add(flooper);
}
else if (bleep.equals("2")){
twoStarList.add(flooper);
}
else if (bleep.equals("3")){
threeStarList.add(flooper);
}
else if (bleep.equals("4")){
fourStarList.add(flooper);
}
else if (bleep.equals("5")){
fiveStarList.add(flooper);
}
grandTotal+=(Double.parseDouble(bloop[2]));
}
}
catch (Exception e){
}
Map<String,List<String>> hmap = new HashMap<String,List<String>>();
hmap.put("1",oneStarList);
hmap.put("2", twoStarList);
hmap.put("3", threeStarList);
hmap.put("4", fourStarList);
hmap.put("5", fiveStarList);
while ((line2=br2.readLine()) != null) {
splitInput = new String[5];
splitInput = line2.split("\\s+");
evaluate(splitInput[0],splitInput[1],hmap);
}
br.close();
br2.close();
}
public static void evaluate(String movID, String usrID, Map<String,List<String>> hash) throws Exception{
FileWriter fw = new FileWriter("outputTest.txt");
BufferedWriter bwr = new BufferedWriter(fw);
List<String> values = new ArrayList<String>();
List<String> outputList = new ArrayList<String>();
String[] floop;
String fleep;
int movIDtotal=0;
int usrIDtotal=0;
int totalValues=0;
double pmovIDStar=0;
double pusrIDStar=0;
double pmovID=0;
double pusrID=0;
double numID=0;
double keyTotalProb=0;
String keyOutputStr;
String keyHold;
final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();
for (String key : hash.keySet()){
values = hash.get(key);
System.out.println(key + ":");
for (int i=0;i<values.size();i++){
System.out.println(values.get(i));
floop = new String[5];
fleep = values.get(i);
floop = fleep.split("\\s+");
if (movID.equals(floop[0])){
movIDtotal++;
totalValues++;
}
if (usrID.equals(floop[0])){
usrIDtotal++;
totalValues++;
}
}
values.clear();
}
for (Map.Entry<String, List<String>> entry: entries){
values= entry.getValue();
keyHold = entry.getKey();
for (int j=0;j<values.size();j++){
floop = new String[5];
fleep = values.get(j);
floop = fleep.split("\\s+");
if (movID.equals(floop[0])){
pmovIDStar = Double.parseDouble(floop[3]);
numID = Double.parseDouble(floop[1]);
pmovID = (numID/movIDtotal);
}
if (usrID.equals(floop[0])){
pusrIDStar = Double.parseDouble(floop[3]);
numID = Double.parseDouble(floop[1]);
pusrID = (numID/usrIDtotal);
}
}
keyTotalProb = ((totalValues/grandTotal)*(pmovIDStar)*(pusrIDStar))/(pusrID*pmovID);
keyOutputStr = Double.toString(keyTotalProb);
outputList.add(keyHold);
outputList.add(keyOutputStr);
values.clear();
}
double max = Double.MIN_VALUE;
for (int m=0;m<outputList.size();m+=2){
double coolguy = Double.parseDouble(outputList.get(m+1));
int index = 0;
if(coolguy>max){
max = coolguy;
index = m;
}
try {
bwr.write(String.format("%-1s %-1s %-1s%n", movID,usrID,outputList.get(index)));
bwr.close();
fw.close();
}
catch(Exception e) {
}
}
}
}
Backup info: I'm trying to build a java program that essentially performs the final stage of the Naive Bayes algorithm to predict user ratings (1-5) for movies. I have used MapReduce to train data and now I have an input file where each line contains a string containing information in this order without the commas (movie or user id,rating , number of times rating and ID occur together in total, number of times ID occurs in total, probability that ID and rating occur together out of all ratings for ID). Essentially this is the classification stage.
never suppress excetions. especially when you do coding/debugging.
catch (Exception e){ } is very bad practice
When you do:
final Set<Map.Entry<String,List<String>>> entries = hash.entrySet();
it does not copy hash.entrySet to entries. It creates another reference to it.
same is for values= entry.getValue();
then what do you expect after your first loop (and others too)?
when you do:
values.clear();
your values gone from the lists which are in hash and since entries is just a reference to hash.entrySet() you have what you've done - empty lists.
So I have to read out a string from a file in Java. It's for a highscore system.
Each line of the file contains something similiar like this: "24/Kilian".
The number in front of the / is the score and the text after the / is the name.
Now, my problem is that I have to sort the scores descending and write them back into the file. The new scores should overwrite the old ones.
I tried it but I can't get it working properly.
I already wrote some code which reads the score + name line by line out of the file.
public static void sortScores() {
String [][]scores = null;
int i = 1;
try (BufferedReader br = new BufferedReader(new FileReader("score.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
scores[i][0] = line.substring(0, line.indexOf("/"));
scores[i][1] = line.substring(line.indexOf("/"), line.length());
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
So, this code basically writes the score and the name in a 2D array like this:
score[0][0] = "24";
score[0][1] = "Kilian";
score[1][0] = "33";
score[1][1] = "Name";
score[2][0] = "45";
score[2][1] = "AnotherName";
I hope someone can help me with my problem.
You can use java.util.Arrays's sort-Method:
Arrays.sort(scores, (a, b) -> -a[0].compareTo(b[0]));
But this lead to the case that "3" will be above "23". So probably you should create new class which holds the value and use an ArrayList
I'd recomend you to make a new class Score which holds your data (score + name) and add a new instance of Score into a ArrayList for each row you read from the file. After that you can implement a Comparator and sort your ArrayList. It's much easier because you don't know how big your string array will get and you need to know that when you're working with arrays.
public class Score {
public Score(int score, String name) {
this.score = score;
this.name = name;
}
int score;
String name;
// getter
}
List<Score> scoreList = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
scoreList.add(new Score(Integer.parseInt(line.substring(0, line.indexOf("/"))), line.substring(line.indexOf("/"), line.length())));
}
Collections.sort(scoreList, new Comparator<Score>() {
public int compare(Score s1, Score s2) {
return s1.getScore() - s2.getScore();
}
}
// write to file
You can try it:
HashMap<Integer, String > map = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader("score.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] lines = line.split("/");
map.put(Integer.valueOf(lines[0]),lines[1]);
}
SortedSet<Integer> keys = new TreeSet<Integer>(map.keySet());
keys.forEach(k -> System.out.println(map.get(k).toString() + " value " + k ));
Use Arrays.sort(arr, comparator) with a custom comparator:
Arrays.sort(theArray, new Comparator<String[]>(){
#Override
public int compare(final String[] first, final String[] second){
// here you should usually check that first and second
// a) are not null and b) have at least two items
// updated after comments: comparing Double, not Strings
// makes more sense, thanks Bart Kiers
return Double.valueOf(second[1]).compareTo(
Double.valueOf(first[1])
);
}
});
System.out.println(Arrays.deepToString(theArray));
I'm having some trouble accessing my 2D array (myArray) outside of this the loop. I want to access it using other methods, but I can't even access it in this method. It prints out correctly as it's looping, but the test print of
System.out.println(myArray[10][2]);
is always null. So it's like the array isn't actually filling or something. Anyone know what I'm doing wrong here?
package titanic;
import java.io.*;
import java.util.*;
public class Titanic {
public static final int ROW = 1309;
public static final int COLUMN = 6;
public static String [][] myArray = new String[ROW][COLUMN];
public static String[][] arraySetup(){
int recordCounter = 0;
String[][] myArray = new String[ROW][COLUMN];
String[] name = new String [ROW];
try {
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Tom/Desktop/Titanic.txt"));
String line;
for (int i = 0; i < 1309; i++){
while((line = br.readLine()) != null){
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(myArray[10][2]);
System.out.println(recordCounter + " records.");
return myArray;
}
As you have you while loop inside for loop that is used to for indexing your output array while loop always writes into the myArray[0][0] to myArray[0][5]
for (int i = 0; i < 1309; i++){ // i is 0
while((line = br.readLine()) != null){ // you go through all the lines while i is 0
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
Because of that your check always returns null.
System.out.println(myArray[10][2]);
I think the problem in your code is right there
for (int i = 0; i < 1309; i++){ // you loop 1308 time
while((line = br.readLine()) != null){ /* in each loop, you loop
until you have read all the file so you read 1308 time the file. But when
you reach the end of file on the first iterration, it wont read the file on the 1307
other iterration and all data will be store in myArray[0][0-5]*/
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
Don't use for and while loop together. During the first for loop, your while reads all file contents and all other array positions remain empty.
Try this instead:
int i=0;
while ((line = br.readLine()) != null){
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
...
myArray[i][5] = tmp[5];
i++;
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
Code so far:
public class test1 {
public static void main(String[] args) throws IOException {
//declare reader and writer
BufferedReader reader = null;
PrintWriter writer = null;
//hash maps to store the data
HashMap<String, String> names = new HashMap<String, String>();
//read the first file and store the data
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("IRStudents.txt"))));
String line;
String[] arg;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("-")) {
arg = line.split(" ");
names.put(arg[0], arg[1]);
}
}
reader.close();
//read the second file, merge the data and output the data to the out file
writer = new PrintWriter(new FileOutputStream(new File("File_2.txt")));
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("Marks.txt"))));
while((line = reader.readLine()) != null){
arg = line.split(" ");
writer.println(arg[0] + " " + names.get(arg[0]));
writer.println("Marks: " + arg[1]);
writer.println("- - - - - -");
}
writer.flush();
writer.close();
reader.close();
}
}
So the output in the text file looks like:
25220 Fiona
Marks: 68.3
- - - - - -
25212 Greg
Marks: 70.5
- - - - - -
I have ANOTHER text file with another set of marks with the same layout as the first mark file.
Now I want to add a new set of marks to the set of data So it should look like this:
25220 Fiona
Marks: 68.3 Marks2: 21.2
- - - - - -
25212 Greg
Marks: 70.5 Marks2: 23.43
- - - - - -
So what can I do to add? I assume I have to add a new Hashmap for the new text document? But when I tried doing all of that it never fully works.
IR Student:
25987 Alan
25954 Betty
25654 Chris
25622 David
You could do the following too.
package toBeDeleted;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MarksProcessor {
private final Map<String, Record> map = new HashMap<>();
public static void main(String[] args) {
String fileName = "file1.txt"; // change it to your specific file.
MarksProcessor marksProcessor = new MarksProcessor();
marksProcessor.processFile(fileName, 0);
fileName = "file2.txt";
marksProcessor.processFile(fileName, 1);
marksProcessor.writeData();
}
private void processFile(String fileName, int marksIndex) {
try(/*specify your reader resources here*/) {
// read the first record and get rollNumber, name and marks.
String roll = "valueYouGot";
double value = 0.0; // the value you read.
Record record = map.get(roll);
// if record is null, you need to create one
// and put it into the map.
//record.updateMarks(marksndex, value);
}
}
private void writeData() {
// if this needs to be written to a file/stream, create a writer.
for (Map.Entry<String, Record> entry : map.entrySet()) {
String roll = entry.getKey();
Record record = entry.getValue();
if (record != null) {
String name = record.getName();
double marks1 = record.getMarks(0);
double marks2 = record.getMarks(1);
// Now you have all the values. Print them
// however you like. Wherever you like.
}
}
}
static class Record {
private String name;
private double[] marks = new double[2];
Record(String name) {
this.name = name;
}
public String getName() {
return name;
}
public double getMarks(int index) {
if (index < 0 || index > 1)
throw new IllegalArgumentException("index should be 0 or 1 but"
+ " the supplied index was " + index);
return marks[index];
}
public void updateMarks(int index, double value ) {
if (index < 0 || index > 1)
throw new IllegalArgumentException("index should be 0 or 1 but"
+ " the supplied index was " + index);
marks[index] = value;
}
#Override
public String toString() {
return "the way you want to type your output";
}
}
}
I think you are doing too much String manipulation. And if you will have more marks' files to process in a similar way, the String manipulation is likely going to increase which could make your code less readable and could give more room for errors. I think following would be a better approach.
You could create a MarksRecord class with the following structure.
public class MarksRecord {
private String subject; // or whatever this variable name should be.
// in your case it should hold value marks1.
private double marks;
}
Similarly you could create an immutable Student/similar class as follows. This could be a value class with equals and hashCode methods based on the first number you are reading in each file. I am guessing it is roll number or similar that can identify a student in a unique way.
public final class Student {
private final String rollNumber;
private final String name;
// equals, hashCode, and other methods.
}
Then in your main method you could have a
Map<Student, ArrayList<MarksRecord>>
. Alternatively you could also use a
Map<String, ArrayList<MarksRecord>>
where the first String is the roll number of a Student record.
This way every time you have a new file of marks, your data structure will be able to accomodate it.
When adding the new marks, use this to add them to the already existing ones:
String key = arg[0];
String secondMarks = arg[1];
String theMarks = names.get(key);
theMarks = theMarks + " Marks2: " + secondMarks;
names.put(key, theMarks);
I think I understand your problem, let me know if this is incorrect.
The requirement is to have all marks that the person receved on its own line...
Theres two print functions in the System.out stream.
print and println
arg = line.split(" ");
writer.println(arg[0] + " " + names.get(arg[0]));
writer.print("Marks: " + arg[1]);
for(int i = 2; i < args.length; i++){
writer.println(" Marks" + i + ": " + arg[i]);
}
writer.println("\n- - - - - -");