How to store info from an Array to an Array Object? - java

I have a Java class which uses BufferedReader to obtain information from a text file, then store the information into an Array called newData . I want to store a certain part of the information to the VegTypes[f] = new VegType(); but I not sure what code should I write here to obtain that part of information.
Without completing this part, I am not able to continue working on another Array Object which is Vegs[i] = new Veg(newData[0], newData[1], newData[2],); for storing information together with VegTypes Array Object.
Below is my code of the Java class:
public class theVegetable {
private Veg[] Vegs;
private VegType[] VegTypes;
public theVegetable() {
int quantity;
int vegQuantity;
String vegLine;
try {
BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
quantity = Integer.parseInt(vegLine.readLine());
Vegs = new Veg[quantity];
for (int i = 0; i < quantity; i++) {
vegLine = br.readLine();
String[] newData = vegLine.split(";");
vegQuantity = Integer.parseInt(newData[3]);
//For loop to store information into VegTypes
for (int f = 0; j < vegQuantity; f++) {
VegTypes[f] = new VegType();
}
//Vegs Array Object to store information plus VegTypes
Vegs[i] = new Veg(newData[0], newData[1], newData[2],);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
Below is my vegetableInfo.txt text file:
3
Tomato;class1;Malaysia Tomato;2;MT100A;MT1;200;90;MT20A;MT2;600;80;Malaysia product
Avocado;class2;Europe Avocado;4;EA100A;EA1;300;90;EA14A;EA2;90;80;EA230A;EA3;43;50.9;EA470A;EA4;400;76;Europe product
Cabbage;class3;Malaysia Cabbage;3;MC100A;MC1;500;20;MC49A;MC2;500;50;MC800A;MC3;600;10.3;Malaysia product
The number 3 at the top of the text file is for the int quantity; variable to store the amount.
The kind of information I want the VegTypes[f] = new VegType(); to store are MT100A;MT1;200;90;MT20A;MT2;600;80;, the number 2 besides the Malaysia Tomato are for int vegQuantity; variable. Same thing goes for other vegetables in the text file.
Constructor of my private VegType[] VegTypes; Array Object:
private String vegCode;
private String vegBatch;
private int vegBatchQuantity;
private double vegGrade;
public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
vegCode = inVegCode;
vegBatch = inVegBatch;
vegBatchQuantity = inVegBatchQuantity;
vegGrade = inVegGrade;
}
My Veg Class:
public class Veg {
private String vegetableName;
private String classLevel;
private String productionCountry;
private VegType[] VegTypes;
private String productType;
//Constructor
public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
vegetableName = inVegetableName;
classLevel = inClassLevel;
productionCountry = inProductionCountry;
vegType = inVegTypes;
productType = inProductType;
}
public String getVegetableName() {
return vegetableName;
}
public String getClassLevel() {
return classLevel;
}
public String getProductionCountry() {
return productionCountry;
}
public String getProductType() {
return productType;
}
}

This is wrong:
//For loop to store information into VegTypes
for (int f = 0; j < vegQuantity; f++) {
VegTypes[f] = new VegType();
}
you need to use f to adjust the index into your array of fields.
for (int f = 0; j < vegQuantity; f++) {
String vegCode = newLine[f*4 + 4];
String vegBatch = newLine[f*4 + 5];
int vegQuantity = Integer.parse(newLine[f*4 + 6]);
double vegGrade = Double.parse(newLine[f*4 + 7]);
VegTypes[f] = new VegType(vegCode, vegBatch, vegQuantity, vegGrade);
}

class VegType {
private String vegCode;
private String vegBatch;
private int vegBatchQuantity;
private double vegGrade;
public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
vegCode = inVegCode;
vegBatch = inVegBatch;
vegBatchQuantity = inVegBatchQuantity;
vegGrade = inVegGrade;
}
#Override
public String toString() {
return vegCode+" "+vegBatch+" "+vegBatchQuantity+" "+vegGrade;
}
}
class Veg {
private String vegetableName;
private String classLevel;
private String productionCountry;
private VegType[] VegTypes;
private String productType;
//Constructor
public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
vegetableName = inVegetableName;
classLevel = inClassLevel;
productionCountry = inProductionCountry;
VegTypes = inVegTypes;
productType = inProductType;
}
#Override
public String toString() {
return vegetableName+" "+classLevel+" "+productionCountry+" "+VegTypes+" "+productType;
}
public String getVegetableName() {
return vegetableName;
}
public String getClassLevel() {
return classLevel;
}
public String getProductionCountry() {
return productionCountry;
}
public String getProductType() {
return productType;
}
}
class TheVegetable {
private Veg[] Vegs;
private VegType[] VegTypes;
public TheVegetable() throws IOException {
int quantity;
int vegQuantity;
String vegLine;
try {
BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
quantity = Integer.parseInt(br.readLine());
Vegs = new Veg[quantity];
for (int i=0; i<quantity; i++) {
vegLine = br.readLine();
String[] newData = vegLine.split(";");
vegQuantity = Integer.parseInt(newData[3]);
VegTypes=new VegType[vegQuantity];
for(int j=4, k=0; j<newData.length-1; j+=4, k++) {
VegTypes[k] = new VegType(newData[j], newData[j+1], Integer.parseInt(newData[j+2]), Double.parseDouble(newData[j+3]));
}
Vegs[i]=new Veg(newData[0], newData[1], newData[2], VegTypes, newData[newData.length-1]);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}

Related

Turn Enum into a Class in Java

I have a class that has an enum declared in it, like this:
private enum Marker {
NONE {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
return null;
}
},
STRING {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = value;
buf[COLUMN_VALUE_FLOAT] = "";
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
},
FLOAT {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = "";
buf[COLUMN_VALUE_FLOAT] = value;
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
};
public abstract String[] createResultLine(String columnName, String value, String[] buf);
}
and here is the complete class and the usage
final class CSVDataModifier {
private final Path src;
private int rowNumber = 0;
private static String blockId = "" ;
private static String pipelineId = "" ;
private static String ElasticHostURL = "";
public CSVDataModifier(Path src, /*Path dest, */ String b_id, String p_id, String elasticUrl) {
this.src = src;
this.blockId = b_id;
this.pipelineId = p_id;
this.ElasticHostURL = elasticUrl;
}
private static final int ROW_NUMBER = 0;
private static final int COLUMN_NAME = 1;
private static final int COLUMN_VALUE_STRING = 2;
private static final int COLUMN_VALUE_FLOAT = 3;
private static final int BLOCK_ID = 4;
private static final int PIPELINE_ID = 5;
private static final String[] COLUMN_NAMES = { "row_number", "column_name", "column_value_string", "column_value_float", "blockId", "pipelineId" };
private ExecutorService executorService = Executors.newFixedThreadPool( 100 );
public void apply() throws IOException, InterruptedException {
try (CSVReader reader = new CSVReader(new FileReader(src.toFile())))
{
List<String[]> csvLines = new ArrayList<>();
// key - ordered list of columns in source file
Map<String, Marker> columnNameFloatMarker = getSourceColumnNamesWithFloatMarker(reader.readNext());
int posRowNumber = getRowNumberPosition(columnNameFloatMarker.keySet());
if (columnNameFloatMarker.isEmpty()) {
System.out.println( "empty!" );
return;
}
String[] buf = new String[COLUMN_NAMES.length];
reader.forEach(values -> {
buf[ROW_NUMBER] = values[posRowNumber];
int col = 0;
String[] resultLine;
for (Map.Entry<String, Marker> entry : columnNameFloatMarker.entrySet()) {
String columnName = entry.getKey();
Marker marker = entry.getValue();
if ((resultLine = marker.createResultLine(columnName, values[col], buf)) != null) {
// writer.writeNext( resultLine );
csvLines.add( resultLine );
rowNumber++;
}
col++;
}
if (csvLines.size() >= 75)
{
List<String[]> tmp = new ArrayList<>( );
tmp.addAll( csvLines );
csvLines.clear();
executorService.execute(new BulkThread(ElasticHostURL, new ArrayList<>( tmp )));
}
});
if (csvLines.size() > 0) {
List<String[]> tmp = new ArrayList<>( );
tmp.addAll( csvLines );
csvLines.clear();
executorService.execute(new BulkThread(ElasticHostURL, new ArrayList<>( tmp )));
}
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.println( "Total Lines: " + rowNumber );
}
private static final String FLOAT = "_float";
private static final String STRING = "_string";
private enum Marker {
NONE {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
return null;
}
},
STRING {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = value;
buf[COLUMN_VALUE_FLOAT] = "";
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
},
FLOAT {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = "";
buf[COLUMN_VALUE_FLOAT] = value;
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
};
public abstract String[] createResultLine(String columnName, String value, String[] buf);
}
// Source column pre-processing to avoid string comparision;
private static Map<String, Marker> getSourceColumnNamesWithFloatMarker(String... columns) {
if (columns == null || columns.length == 0)
return Collections.emptyMap();
Map<String, Marker> map = new LinkedHashMap<>();
for (int i = 0; i < columns.length; i++) {
String columnName = columns[i];
Marker marker = Marker.NONE;
if (columnName.endsWith(FLOAT)) {
columnName = columnName.substring(0, columnName.length() - FLOAT.length());
marker = Marker.FLOAT;
} else if (columnName.endsWith(STRING)) {
columnName = columnName.substring(0, columnName.length() - STRING.length());
marker = Marker.STRING;
}
if (map.put(columnName, marker) != null)
throw new IllegalArgumentException("Column duplication in the source file");
}
return map;
}
private static int getRowNumberPosition(Set<String> columnNames) {
int i = 0;
for (String columnName : columnNames) {
if ("row_number".equals(columnName))
return i;
i++;
}
throw new IllegalArgumentException("Source file does not contain 'row_number' column");
}
}
The problem is that the private members
private static String blockId = "" ;
private static String pipelineId = "" ;
can't be referenced in the private enum Marker if they're not static, and also they're being initialized in the constructor
public CSVDataModifier(Path src, /*Path dest, */ String b_id, String p_id, String elasticUrl) {
this.src = src;
this.blockId = b_id;
this.pipelineId = p_id;
this.ElasticHostURL = elasticUrl;
}
I can see the only way to do that, to declare the private member not as static , is to turn the private enum Marker into an internal class or maybe something else.
Since I'm new to Java and to the OOP world, can I get any guidance to solve this issue?
This code is quite hardcore and needs massive refactoring because it is violating most of programming principles
The answer for your question is to extract those fields to another class like ModifierSetup and provide it to the createResultLine as a parameter
public class ModifierSetup {
private String pipelineId;
private String ElasticHostURL;
// all args constructor
}
// inside your CSVDataModifier
private ModifierSetup setup;
public CSVDataModifier(Path src, /*Path dest, */ String b_id, String p_id, String elasticUrl) {
this.src = src;
this.blockId = b_id;
this.setup = new ModifierSetup(p_id, elasticUrl);
}
// ...
if ((resultLine = marker.createResultLine(columnName, values[col], buf, this.setup)) != null) {
// ...
public abstract String[] createResultLine(String columnName, String value, String[] buf, ModifierSetup modifierSetup);
but that's definitely not enough. Many of your fields should be extracted like this. Instead of weird 'singleton' enum implementation you should provide some common interface like
public interface ResultLineCreator {
ResultData createResultLine(ColumnMetaData columnMetaData, ModifierSetup modifierSetup, ResultData result); // in ColumnMetaData you can encapsulate columnName and value, inside ResultData result data
}
and proper local implementations of it, the reader should be wrapped with some kind of supplier etc etc - just think about how many responsibilities this class has - even if you will resolve your problem it won't be working/maintanable/testable/clear

Read rows from a text file and sort the values from rows by mean (average) by writing them in a new text file

I have a text file, which contains the following text:
Input.txt:
name s1 s2 s3 s4
Jack 2 4 6 5
Alex 3 5 5 5
Brian 6 6 4 5
Now the highest average is for Brian: 5.2; Alex: 4.5; Jack: 4.25.
My task is to get the average number for each Person and then sort people by ascending average score, then create a new text file with the sorted values.
The above example must look like this in the new text file.
Output.txt:
name s1 s2 s3 s4
Brian 6 6 4 5
Alex 3 5 5 5
Jack 2 4 6 5
So far I came up with 2 solutions, none of which can make the task to its end.
The first one is:
public class Sort {
public static void main(String[] args) throws IOException {
int sortKeyIndex = 0;
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = Paths.get("C:\\Users\\Desktop\\new-sample.txt");
String separator = " ";
Stream<CharSequence> sortedLines =
Files.lines(inputFile)
.skip(1)
.map(sorting -> sorting.split(separator))
.sorted(Comparator.comparing(sorting -> sorting[sortKeyIndex]))
.map(sorting -> String.join(separator, sorting));
Files.write(outputFile, sortedLines::iterator, StandardOpenOption.CREATE);
}
}
The second one is:
public class SortTestSecond {
private static BufferedReader theReader;
public static void main(String[] args) throws IOException {
try {
theReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test2.txt"));
theReader.readLine();
String currLine = null;
while((currLine = theReader.readLine()) != null) {
System.out.println(currLine);
StringTokenizer strTok = new StringTokenizer(currLine, " ");
int theCount=strTok.countTokens();
int theArray[]=new int[theCount];
int i = 0;
while(strTok.hasMoreTokens() && i != theCount) {
theArray[i]=Integer.valueOf(strTok.nextToken());
i = i + 1;
}
int theSum = 0;
for(int j =0;j < theArray.length; j++) {
theSum = theSum + theArray[j];
}
float average = (float) theSum / theArray.length;
System.out.println("Average: " + average);
}
} catch(IOException err) {
err.printStackTrace();
} finally {
theReader.close();
}
}
}
One variant would be
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = inputFile.resolveSibling("new-sample.txt");
String separator = " ", newLine = System.getProperty("line.separator");
Pattern p = Pattern.compile(separator);
try(BufferedReader br = Files.newBufferedReader(inputFile);
BufferedWriter bw = Files.newBufferedWriter(outputFile, StandardOpenOption.CREATE)) {
bw.append(br.readLine()).append(newLine); // header
br.lines()
.sorted(Comparator.comparingDouble(line ->
-p.splitAsStream(line).skip(1).mapToInt(Integer::parseInt).average().orElse(-1)))
.forEachOrdered(s -> {
try { bw.append(s).append(newLine); }
catch(IOException ex) { throw new UncheckedIOException(ex); }
});
}
However, the sorting operation requires the data in memory anyway, even if it looks like fluent streaming, it’s just hidden here. If we accept the fact that we will have the entire data in memory, we can simplify the entire operation as:
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = inputFile.resolveSibling("new-sample.txt");
String separator = " ";
Pattern p = Pattern.compile(separator);
List<String> lines = Files.readAllLines(inputFile);
lines.subList(1, lines.size())
.sort(Comparator.comparingDouble(line ->
-p.splitAsStream(line).skip(1).mapToInt(Integer::parseInt).average().orElse(-1)));
Files.write(outputFile, lines, StandardOpenOption.CREATE);
You will have to create a class called Candidate which implements Comparable
class Candidate implements Comparable {
String name;
int [] values;
float average;
}
Candidate(String Name, int [] values) {
this.name = Name;
this.values = values;
this.average = getAverage();
}
public float getAverage() {
int sum = 0;
for(int c : values) {
sum += c;
}
return (float) sum/values.length;
}
#override
public int compareTo(Candidate c) {
if(c.average>this.average){
return 1;
} else {
return -1;
}
}
}
Coming to your main class you need to create an object for each line and populate with the constructor.
class main {
HashMap<String, Candidate> candidateList = new HashMap<String, Candidate>();
public static void main(String args[]) {
String FILENAME = "E:\\test\\filename.txt";
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String [] currentLine = sCurrentLine.split(" ");
String name = currentLine[0];
int [] values = new int[currentLine.length-1];
for(int i=1; i<currentLine.length; i++) {
values[i-1] = Integer.valueOf(currentLine[i]);
}
Candidate c = new Candidate(name,values);
candidateList.put(name,c);// file converted to a list of candidates
}
}
}
Sort that file and print it to a new file.
You can use this approach:
package com.grsdev.stackoverflow.question180629.pack01;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ScoreTransformer {
private final static String INPUT_FILE="input.txt";
private final static String OUTPUT_FILE="output.txt";
private final static String SEPARATOR=" ";
public static void main(String[] args) throws IOException, URISyntaxException {
Path inputPath=Paths.get(INPUT_FILE));
Stream<String> sorted= Files
.lines(inputPath)
.skip(1)
.map(t->PersonConvertor.parseStringToPerson(t, SEPARATOR))
.sorted((p1,p2)->(int)(p2.getAverageScore()-p1.getAverageScore()))
.map(p->PersonConvertor.convertToString(p, SEPARATOR));
Files.write(Paths.get(OUTPUT_FILE), sorted.collect(Collectors.toList()));
}
}
class PersonConvertor {
public static Person parseStringToPerson(String line,String separator) {
Person blankPerson = new Person(null, 0, 0, 0, 0);
if(line==null) return blankPerson;
String[] array = line.split(separator);
if(array.length==5) {
return new Person (array[0],Integer.parseInt(array[1]),Integer.parseInt(array[2]),Integer.parseInt(array[3]),Integer.parseInt(array[4]));
}
return blankPerson;
}
public static String convertToString(Person p,String separator) {
if(p==null)return "";
String line=p.getName()+separator+p.getScore1()+separator+p.getScore2()+ separator+p.getScore3()+separator+p.getScore4();
return line;
}
}
class Person implements Comparable<Person>{
private String name;
private int score1,score2,score3,score4;
private float averageScore;
public Person(String name, int score1, int score2, int score3, int score4) {
super();
this.name = name;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
this.score4 = score4;
setAverageScore(((getScore1()+getScore2()+getScore3()+getScore4())/4));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore1() {
return score1;
}
public void setScore1(int score1) {
this.score1 = score1;
}
public int getScore2() {
return score2;
}
public void setScore2(int score2) {
this.score2 = score2;
}
public int getScore3() {
return score3;
}
public void setScore3(int score3) {
this.score3 = score3;
}
public int getScore4() {
return score4;
}
public void setScore4(int score4) {
this.score4 = score4;
}
public float getAverageScore() {
return averageScore;
}
public void setAverageScore(float averageScore) {
this.averageScore = averageScore;
}
public int compareTo(Person p) {
return (int) (this.averageScore-p.getAverageScore());
}
#Override
public String toString() {
return "Person name=" + name + ", score1=" + score1 + ", score2=" + score2 + ", score3=" + score3 + ", score4="
+ score4 + ", averageScore=" + averageScore + "]";
}
}
You can try this out. Firstly read each line of file and then map it to a Person class. Then sort each Person based on the sum of four values, since it ramifies the average order. Finally collect the sorted objects as a String. The last is to write that String representation of sorted Person objects into a file. Also it's worth using Java 8 for this.
try (Stream<String> stream = Files.lines(Paths.get("C:\\data\\sample.txt"))) {
final String sortedPeople = stream.skip(1).map(l -> l.split(" "))
.map(a -> new Person(a[0], Integer.parseInt(a[1]), Integer.parseInt(a[2]), Integer.parseInt(a[3]),
Integer.parseInt(a[4])))
.sorted(Comparator.comparingInt(Person::sum).reversed()).map(Person::toString)
.collect(Collectors.joining("\n"));
System.out.println(sortedPeople);
Path path = Paths.get("C:\\data\\new-sample.txt");
byte[] strToBytes = sortedPeople.getBytes();
Files.write(path, strToBytes);
} catch (IOException e) {
e.printStackTrace();
}
public class Person {
private final String name;
private final int valOne;
private final int valTwo;
private final int valThree;
private final int valFour;
public Person(String name, int valOne, int valTwo, int valThree, int valFour) {
super();
this.name = name;
this.valOne = valOne;
this.valTwo = valTwo;
this.valThree = valThree;
this.valFour = valFour;
}
public String getName() {
return name;
}
public int getValOne() {
return valOne;
}
public int getValTwo() {
return valTwo;
}
public int getValThree() {
return valThree;
}
public int getValFour() {
return valFour;
}
public int sum() {
return this.valOne + this.valTwo + this.valThree + this.valFour;
}
#Override
public String toString() {
return name + ", " + valOne + ", " + valTwo + ", " + valThree + ", " + valFour;
}
}
Output
Brian, 6, 6, 4, 5
Alex, 3, 5, 5, 5
Jack, 2, 4, 6, 5

How to sort content of a csv file in java

I have a big csv file that looks like this
Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology
I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far
package project1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
int choice=0;
boolean flag = true;
while (flag) {
System.out.println("Enter 1 to display data.");
System.out.println("Enter 2 to sort data.");
System.out.println("Enter 3 to idk.");
System.out.println("Enter 0 to exit.");
System.out.print("Your choice: ");
choice = input.nextInt();
if (choice ==1) {
File inputFile = new File("dataToLoad.csv");
String line;
String delimiter = ",";
Scanner in = new Scanner(inputFile);
int numberOfLines = 0;
int numberOfColumns = 0;
while (in.hasNextLine()){
line = in.nextLine();
numberOfLines++;
}
in.close();
String[][] data = new String[numberOfLines][8];
in = new Scanner(inputFile);
int currentRow = 0;
while (in.hasNextLine()){
line = in.nextLine();
String[] parts = line.split(delimiter);
numberOfColumns = parts.length;
for (int i = 0; i<numberOfColumns; i++) {
data[currentRow][i] = parts[i];
}
currentRow++;
}
in.close();
System.out.println(Arrays.deepToString(data));
for (int row=0; row<numberOfLines; row++) {
for (int col=0; col<numberOfColumns; col++) {
System.out.printf("%-20s", data[row][col]);
}
System.out.println();
}
}
else {
if (choice ==2) {
}
else
if (choice==0) {
System.out.println("Good bye!");
flag = false;
}
else System.out.println("I am sorry, this is not a valid option. Please try again.");
}
}
}
}
As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.
Stop reinventing the wheel; use a csv open source library (for example, opencsv).
Create a class that represents one row of data in your csv file; I'll refer to this as RowClass.
Read the CSV file one row at a time. Each row will arrive as a String[].
Create and populate one instance of RowClass per row of the CSV file.
Store the RowClass objects in a List; I'll call this rowList.
Sort rowList using a Comparator that you create. Create one Comparator for each sort option.
Implement RowClass.toString() to display one row.
This should help, I believe that you will figure out what's going on here
Main.java
package pkg;
import java.util.Arrays;
import static pkg.Order.OrderBuilder;
public class Main {
private static Order[] orders = new Order[3];
private static OrderBuilder orderBuilder = new OrderBuilder();
public static void main(String[] args) {
Order order1 = orderBuilder.createNewOrder().withId(10).withCustomerName("John").withPrice(1.23f).withPriority("high").build();
Order order2 = orderBuilder.createNewOrder().withId(20).withCustomerName("Lee").withQuantity(3.4f).build();
Order order3 = orderBuilder.createNewOrder().withId(30).withCustomerName("Someone").withPriority("low").build();
orders[0] = order3;
orders[1] = order1;
orders[2] = order2;
System.out.println("Before sorting");
for(int i = 0; i < orders.length; i++) {
System.out.println(orders[i].getId());
}
Arrays.sort(orders);
System.out.println("After sorting");
for(int i = 0; i < orders.length; i++) {
System.out.println(orders[i].getId());
}
}
}
Order.java
package pkg;
public class Order implements Comparable<Order> {
private int id;
private String priority;
private float quantity;
private float price;
private String shipMode;
private String customerName;
private String customerSegment;
private String productCategory;
private void setId(int id) {
this.id = id;
}
int getId() {
return this.id;
}
private void setPriority(String priority) {
this.priority = priority;
}
private void setQuantity(float quantity) {
this.quantity = quantity;
}
private void setPrice(float price) {
this.price = price;
}
private void setShipMode(String shipMode) {
this.shipMode = shipMode;
}
private void setCustomerName(String customerName) {
this.customerName = customerName;
}
private void setCustomerSegment(String customerSegment) {
this.customerSegment = customerSegment;
}
private void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
#Override
public int compareTo(Order o) {
return this.id - o.getId();
}
static class OrderBuilder {
private Order order;
OrderBuilder withId(int id) {
order.setId(id);
return this;
}
OrderBuilder withPriority(String priority) {
order.setPriority(priority);
return this;
}
OrderBuilder withQuantity(float quantity) {
order.setQuantity(quantity);
return this;
}
OrderBuilder withPrice(float price) {
order.setPrice(price);
return this;
}
OrderBuilder withShipMode(String shipMode) {
order.setShipMode(shipMode);
return this;
}
OrderBuilder withCustomerName(String customerName) {
order.setCustomerName(customerName);
return this;
}
OrderBuilder withCustomerSegment(String customerSegment) {
order.setCustomerSegment(customerSegment);
return this;
}
OrderBuilder withProductCategory(String productCategory) {
order.setProductCategory(productCategory);
return this;
}
OrderBuilder createNewOrder() {
order = new Order();
return this;
}
Order build() {
return order;
}
}
}

convert a integer to array of class type java

I take in a file which has a name (table) and the number of seats:
table1 6
table2 2
table3 4
I have an array of class Reservation which will take in the the name and the seat. I am having trouble converting the number of seats into the array. How do i go about doing so?
public class Reservable {
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
id = fileIn.next();
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i] = seat;
}
}
}
here is my Reservation class:
public class Reservation {
private String name;
private int timeSlot;
private Reservable myReservable;
public Reservation(String name, int timeSlot) {
this.name = name;
this.timeSlot = timeSlot;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(int timeSlot) {
this.timeSlot = timeSlot;
}
public Reservable getMyReservable() {
return myReservable;
}
public void setMyReservable(Reservable myReservable) {
this.myReservable = myReservable;
}
public boolean isActive() {
return false;
}
You can read line by line since your file has a reservation by line.
I propose you to have a Reservation constructor with two parameters (name and nbSeat).
A remark : you array of reservation has a fixed size : 10. If you file has more than 10 elements, a ArrayIndexOutOfBoundsException will be risen.
If the number of reservation may be superior to 10 or is variable, you should use a List rather than a array.
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
int i=0;
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine();
String[] token = line.split("\\s");
String name = token[0];
int nbSeat= Integer.valueOf(token[1)];
// add in your array
Reservation reservation = new Reservation(name,nbSeat);
arrayRes[i] = reservation ;
}
i++;
}
And Reservation :
public class Reservation{
public Reservation(String name, int nbSeat){
this.name=name;
this.nbSeat=nbSeat;
}
}
You need to show us what your Reservation class looks like, but if it uses the conventional getters and setters this is the correct way:
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i].setSeat(seat);
id = fileIn.next();
arrayRes[i].setId(id);
}
}
}

Find higest value among objects created in a class

Can anybody explain how I get the highest value from all the objects I have created in my main class?
In this example I have created 2 students objects in my main class and added some course names and grades.
I have made 2 static arrays to store the information from the different objects but it doesn't return the object with the highest grade.
How do I store the highest grade from the student objects created?
public class CMate {
private static String[] studentName = new String[2];
private static int[][] gradeAssigned = new int[2][3];
private static int higGrade = 0;
private String name;
private int cpr;
private String[] courseName = new String[3];
private int[] grade = new int[3];
private int numberOfCourse;
private int numberOfGrades;
private static int counter = 0;
CMate(String name, int cpr) {
// building constructor
System.out.println("Creating object nr " + counter);
this.name = name;
this.cpr = cpr;
// insert name into array
studentName[counter] = name;
for (int i = 0; i < numberOfCourse; i++) {
gradeAssigned[counter][i] = grade[i];
}
counter++;
}
public void addcourseName(String nameOfCourse) {
courseName[numberOfCourse] = nameOfCourse;
numberOfCourse++;
}
public void addGrade(int gradeNr) {
grade[numberOfGrades] = gradeNr;
numberOfGrades++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCpr() {
return cpr;
}
public void setCpr(int cpr) {
this.cpr = cpr;
}
public String[] getCourseName() {
return courseName;
}
public void setCourseName(String[] courseName) {
this.courseName = courseName;
}
public int[] getGrade() {
return grade;
}
public void setGrade(int[] grade) {
this.grade = grade;
}
public String toString() {
String studentInfo = "";
System.out.println("------------------------------\n student " + name + " CPR " + cpr);
for (int i = 0; i < numberOfCourse; i++) {
studentInfo += " Course " + courseName[i] + "Grade " + grade[i];
}
return studentInfo;
}
public double averageGrade() {
double total = 0;
for (int i = 0; i < numberOfGrades; i++) {
total += grade[i];
}
return (total / numberOfGrades);
}
public void higestGrade() {
for (int i = 0; i < studentName.length; i++) {
if (grade[i] > higGrade) {
higGrade = grade[i];
}
}
}
public void higestObjectGrade() {
System.out.println(higGrade);
}
}
I don't fully understand your code, but here's a simplified version, including a static field to keep all students, and a static function to return the highest grade:
class Student {
public final static List<Student> allCreatedStudents = new ArrayList<Student>();
String name;
int[] grades = new int[3];
public Student(String name){
this.name = name;
allCreatedStudents.add(this); // Every time a student is created, he is recorded in the static list
}
public void setGrade(int grade, int index){
this.grades[index] = grade;
}
public static int getHighestGrade(){
int highestGrade = 0;
for(Student s : allCreatedStudents){ // Loop through all students
for(int i=0; i<s.grades.length; i++){ // Loop through all grades
if(s.grades[i]>highestGrade)
highestGrade = s.grades[i];
}
}
return highestGrade;
}
}

Categories

Resources