Okay so i have to read data from an CSV file and add methods that calculate which is seen in my code below, so my question is how can i put in output the header of a row (example first,second or third) from which the value has been taken from?
Possibilites | first | second | third| fourth
Decrease | 28 | 24 | 16 | 25
Increase | 30 | 42 | 44 | 45
this is a CSV file im using
My output is like this:
Optimist: first (45)
Pessimist: second (30)
Laplace: third(33)
Least regret: fourth(5)
But i want it to be like this:
Optimist: fourth (45)
Pessimist: first(30)
Laplace: second (33)
Least regret: fourth(5)
package CSVReader;
import java.io.*;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.plaf.FileChooserUI;
import com.opencsv.CSVReader;
public class OpenCSV {
public static void main(String[] args) {
CSVReader reader;
String file = "C:\\Users\\pajov\\Desktop\\osnovne_metode1.csv";
String[] decreaseEconomyAlternatives = null;
String[] increaseEconomyAlternatives = null;
String[] headers = null;
int sizeOfDecisionAlternatives = 0;
try {
reader = new CSVReader(new FileReader(file));
List<String[]> allResults = reader.readAll();
sizeOfDecisionAlternatives = allResults.get(0).length - 1;
headers = allResults.get(0);
decreaseEconomyAlternatives = allResults.get(1);
increaseEconomyAlternatives = allResults.get(2);
System.out.println("Prebrana je bila datoteka: " + file);
for (int i = 1; i <= sizeOfDecisionAlternatives; i++) {
int iterator = i;
System.out.println("Optimist:"+headers[iterator] +" (" + calculationOptist(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
iterator++;
System.out.println("Pessimist:"+headers[iterator] + " (" + calculationPessimist(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
iterator++;
System.out.println("Laplace: "+headers[iterator] + " (" + calculationLaplace(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
iterator++;
System.out.println("Least regret: "+headers[iterator] + " (" + calculationLeastRegret(decreaseEconomyAlternatives, increaseEconomyAlternatives, sizeOfDecisionAlternatives) + ")");
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private static Integer calculationLeastRegret(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfDecreasedValues = new ArrayList<>();
List<Integer> arrayOfIncreasedValues = new ArrayList<>();
List<Integer> maxNumbersOfNewArray = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives + 1; i++) {
arrayOfDecreasedValues.add(Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")));
arrayOfIncreasedValues.add(Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", "")));
}
Integer maxOfDereased = Collections.max(arrayOfDecreasedValues);
Integer maxOfIncreased = Collections.max(arrayOfIncreasedValues);
for (int i = 0; i < sizeOfDecisionAlternatives; i++) {
maxNumbersOfNewArray.add(Math.max((maxOfDereased - arrayOfDecreasedValues.get(i)), (maxOfIncreased - arrayOfIncreasedValues.get(i))));
}
return Collections.min(maxNumbersOfNewArray);
}
private static Integer calculationLaplace(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfNumbers = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives; i++) {
arrayOfNumbers.add((Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")) + Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", ""))) / 2);
}
return Collections.max(arrayOfNumbers);
}
private static Integer calculationPessimist(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfNumbers = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives + 1; i++) {
arrayOfNumbers.add(Math.min(Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")), Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", ""))));
}
return Collections.max(arrayOfNumbers);
}
private static Integer calculationOptist(String[] decreaseEconomyAlternatives, String[] increaseEconomyAlternatives, int sizeOfDecisionAlternatives) {
List<Integer> arrayOfNumbers = new ArrayList<>();
for (int i = 1; i < sizeOfDecisionAlternatives + 1; i++) {
arrayOfNumbers.add(Math.max(Integer.valueOf(decreaseEconomyAlternatives[i].replace(" ", "")), Integer.valueOf(increaseEconomyAlternatives[i].replace(" ", ""))));
}
return Collections.max(arrayOfNumbers);
}
}
Thanks in advance.
Related
I don't know if I'm using the correct way of filtering a barchart, or even if my code is properly written.
But I have problem, when I open my dashboard, I have 3 charts, one of the piecharts can filter the barchart, and depending on which was selected, the barchart only shows the piechart selected, otherwise shows all.
My problem is when I filter those, I'm getting the correct filter, but I can't get the labels to appear, they just appear when I got only one, for example if I have 1Yellow, 15 Reds, its only a bar to show, but it only shows the label for the yellow one, but if yellow2 and 15 reds, it doesn't show any of them.
It should be a easy fix, I just can't see where is the error.
ArrayList<Integer> colors_to_add_type = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MINOR = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MEDIUM = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_MAJOR = new ArrayList<>();
ArrayList<Integer> colors_to_add_type_OTHER = new ArrayList<>();
Iterator<String> defects_colors_keys;
defects_colors_keys = colors_type.keys();
while (defects_colors_keys.hasNext()){
String key = defects_colors_keys.next();
Log.e("COLOR_KEY", "onResponse: " + key );
int to_add = Color.parseColor(colors_type.getString(key));
int to_add_MINOR = Color.parseColor("#00FF00");
int to_add_MEDIUM = Color.parseColor("#FFFF00");
int to_add_MAJOR = Color.parseColor("#FF0000");
int to_add_OTHER = Color.parseColor("#800080");
Log.e("COLOR_NAME", "onResponse: " + colors_type.getString(key));
colors_to_add_type.add(to_add);
colors_to_add_type_MAJOR.add(to_add_MAJOR);
colors_to_add_type_MEDIUM.add(to_add_MEDIUM);
colors_to_add_type_MINOR.add(to_add_MINOR);
colors_to_add_type_OTHER.add(to_add_OTHER);
}
List<LegendEntry> legends_type = new ArrayList<>();
List<LegendEntry> legends_type_MINOR = new ArrayList<>();
List<LegendEntry> legends_type_MEDIUM = new ArrayList<>();
List<LegendEntry> legends_type_MAJOR = new ArrayList<>();
List<LegendEntry> legends_type_OTHER = new ArrayList<>();
type_of_defects = by_type.keys();
int c = 0;
if(!map_defects_by_type_count.isEmpty()){
map_defects_by_type_count.clear();
}
Log.e("DEFECTS", defects_list.toString());
Log.e("DEFECTS",String.valueOf(defects_list.size()));
while(type_of_defects.hasNext()) {
String key = type_of_defects.next();
Log.e("DEFECTS_type", key.toString());
map_defects_by_type_count.put(key, by_type.getInt(key));
map_get_defect_type.put(c, key);
LegendEntry legendEntry = new LegendEntry();
legendEntry.label = key;
legendEntry.formColor = colors_to_add_type.get(c);
legends_type.add(legendEntry);
arr_by_type.add(new BarEntry((float)c + 1, (int)by_type.getInt(key), (String)key));
c++;
for (int i = 0; i < defects_list.size(); i++){
if (defects_list.get(i).getStringProperty("defect").equals(key)){
if (defects_list.get(i).getStringProperty("criticality").equals("MAJOR")){
arr_by_type_MAJOR.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_MAJOR.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("MEDIUM")){
arr_by_type_MEDIUM.add(new BarEntry((float)c +1 , (int)by_type.getInt(key), (String)key));
legends_type_MEDIUM.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("MINOR")){
arr_by_type_MINOR.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_MINOR.add(legendEntry);
break;
}
if (defects_list.get(i).getStringProperty("criticality").equals("OTHER")){
arr_by_type_OTHER.add(new BarEntry((float)c +1, (int)by_type.getInt(key), (String)key));
legends_type_OTHER.add(legendEntry);
break;
}
}
}
}
TOTAL_DEFECTS = TOTAL_BY_CRIT;
if(TOTAL_BY_CRIT != 0){
if(MAJOR != 0){
major_percent = (float) MAJOR / TOTAL_BY_CRIT;
}
if(MEDIUM != 0){
medium_percent = (float) MEDIUM / TOTAL_BY_CRIT;
}
if(MINOR != 0){
minor_percent = (float) MINOR / TOTAL_BY_CRIT;
}
if(OTHER != 0){
other_percent = (float) OTHER / TOTAL_BY_CRIT;
}
}
TOTAL_SOURCE = TOTAL_H_M;
if(TOTAL_H_M != 0){
if(HUMAN != 0){
human_percent = (float) HUMAN / TOTAL_H_M;
}
if(MACHINE != 0){
machine_percent = (float) MACHINE / TOTAL_H_M;
}
}
arr_by_defect.add(new PieEntry(MAJOR, "MAJOR"));
arr_by_defect.add(new PieEntry(MEDIUM, "MEDIUM"));
arr_by_defect.add(new PieEntry(MINOR, "MINOR"));
arr_by_defect.add(new PieEntry(OTHER, "OTHER"));
arr_by_source.add(new PieEntry(HUMAN, "HUMAN"));
arr_by_source.add(new PieEntry(MACHINE, "MACHINE"));
dataSet_by_defect = new PieDataSet(arr_by_defect, "");
dataSet_by_source = new PieDataSet(arr_by_source, "");
dataSet_by_type = new BarDataSet(arr_by_type, "");
dataSet_by_type_MAJOR = new BarDataSet(arr_by_type_MAJOR, "");
dataSet_by_type_MEDIUM = new BarDataSet(arr_by_type_MEDIUM, "");
dataSet_by_type_MINOR = new BarDataSet(arr_by_type_MINOR, "");
dataSet_by_type_OTHER = new BarDataSet(arr_by_type_OTHER, "");
//GET THE COLORS
String colorMajor = colors.getString("MAJOR");
String colorMedium = colors.getString("MEDIUM");
String colorMinor = colors.getString("MINOR");
String colorOther = colors.getString("OTHER");
String colorHuman = human_machine_colors.getString("human");
String colorMachine = human_machine_colors.getString("machine");
final int[] sliceColors = {Color.parseColor(colorMajor), Color.parseColor(colorMedium), Color.parseColor(colorMinor), Color.parseColor(colorOther)};
ArrayList<Integer> colorsSet = new ArrayList<>();
for (int color : sliceColors){
colorsSet.add(color);
}
Log.e("COLORS_TO ADD", "MAJOR" + colorMajor);
Log.e("COLORS_TO ADD", "MEDIUM" + colorMedium);
Log.e("COLORS_TO ADD", "MINOR" + colorMinor);
Log.e("COLORS_TO ADD", "OTHER" + colorOther);
dataSet_by_defect.setColors(colorsSet);
final int[] sliceColors_hm = {Color.parseColor(colorHuman), Color.parseColor(colorMachine)};
ArrayList<Integer> colorsSet_hm = new ArrayList<>();
for (int color : sliceColors_hm){
colorsSet_hm.add(color);
}
dataSet_by_source.setColors(colorsSet_hm);
dataSet_by_type.setColors(colors_to_add_type);
dataSet_by_type_MINOR.setColors(colors_to_add_type_MINOR);
dataSet_by_type_MEDIUM.setColors(colors_to_add_type_MEDIUM);
dataSet_by_type_MAJOR.setColors(colors_to_add_type_MAJOR);
dataSet_by_type_OTHER.setColors(colors_to_add_type_OTHER);
dataSet_by_type.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MINOR.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MEDIUM.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_MAJOR.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet_by_type_OTHER.setAxisDependency(YAxis.AxisDependency.RIGHT);
final PieData data_defect = new PieData(dataSet_by_defect);
final PieData data_source = new PieData(dataSet_by_source);
final BarData data_type = new BarData(dataSet_by_type);
final BarData data_type_MINOR = new BarData(dataSet_by_type_MINOR);
final BarData data_type_MEDIUM = new BarData(dataSet_by_type_MEDIUM);
final BarData data_type_MAJOR = new BarData(dataSet_by_type_MAJOR);
final BarData data_type_OTHER = new BarData(dataSet_by_type_OTHER);
data_type.setDrawValues(true);
data_type_MAJOR.setDrawValues(true);
data_type_MEDIUM.setDrawValues(true);
data_type_MINOR.setDrawValues(true);
data_type_OTHER.setDrawValues(true);
data_defect.setDrawValues(false);
data_source.setDrawValues(false);
//data_type.setBarWidth(.75f);
piechart_defects.setDrawHoleEnabled(true);
piechart_defects.setHoleColor(Color.TRANSPARENT);
piechart_defects.setDrawEntryLabels(false);
piechart_defects.setDrawMarkers(false);
piechart_defects.setCenterText(String.valueOf(TOTAL_DEFECTS) + " TOTAL");
piechart_defects.setCenterTextSize(10);
piechart_defects.getDescription().setEnabled(false);
Legend l_defect = piechart_defects.getLegend();
l_defect.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l_defect.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l_defect.setOrientation(Legend.LegendOrientation.VERTICAL);
l_defect.setDrawInside(false);
l_defect.setEnabled(true);
l_defect.setFormSize(4f);
l_defect.setTextColor(Color.WHITE);
l_defect.setTextSize(.5f);
piechart_source.setDrawHoleEnabled(true);
piechart_source.setDrawEntryLabels(false);
piechart_source.setHoleColor(Color.TRANSPARENT);
piechart_source.setDrawMarkers(false);
piechart_source.setCenterText(String.valueOf(TOTAL_SOURCE) + " TOTAL");
piechart_source.setCenterTextSize(10);
piechart_source.getDescription().setEnabled(false);
piechart_source.setTransparentCircleRadius(10f);
Legend l_source = piechart_source.getLegend();
l_source.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l_source.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l_source.setOrientation(Legend.LegendOrientation.VERTICAL);
l_source.setDrawInside(false);
l_source.setEnabled(true);
l_source.setFormSize(4f);
l_source.setTextColor(Color.WHITE);
l_source.setTextSize(.5f);
dataSet_by_type.setValueTextColor(Color.WHITE);
dataSet_by_type_MAJOR.setValueTextColor(Color.WHITE);
dataSet_by_type_MEDIUM.setValueTextColor(Color.WHITE);
dataSet_by_type_MINOR.setValueTextColor(Color.WHITE);
dataSet_by_type_OTHER.setValueTextColor(Color.WHITE);
dataSet_by_type.setValueTextSize(7f);
dataSet_by_type_MINOR.setValueTextSize(7f);
dataSet_by_type_MEDIUM.setValueTextSize(7f);
dataSet_by_type_MAJOR.setValueTextSize(7f);
dataSet_by_type_OTHER.setValueTextSize(7f);
data_type.setBarWidth(.5f);
data_type.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
Legend l_type_MAJOR = barchart_type.getLegend();
l_type_MAJOR.setCustom(legends_type_MAJOR);
l_type_MAJOR.setWordWrapEnabled(true);
l_type_MAJOR.setDrawInside(true);
data_type_MAJOR.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
data_type_MAJOR.setBarWidth(.5f);
Legend l_type_OTHER = barchart_type.getLegend();
l_type_OTHER.setCustom(legends_type_OTHER);
l_type_OTHER.setWordWrapEnabled(true);
l_type_OTHER.setDrawInside(true);
data_type_OTHER.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
data_type_OTHER.setBarWidth(.5f);
Legend l_type_MINOR = barchart_type.getLegend();
l_type_MINOR.setCustom(legends_type_MINOR);
l_type_MINOR.setWordWrapEnabled(true);
l_type_MINOR.setDrawInside(true);
data_type_MINOR.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
Legend l_type_MEDIUM = barchart_type.getLegend();
l_type_MEDIUM.setCustom(legends_type_MEDIUM);
l_type_MEDIUM.setWordWrapEnabled(true);
l_type_MEDIUM.setDrawInside(true);
data_type_MEDIUM.setValueFormatter(new ValueFormatter() {
#Override
public String getBarLabel(BarEntry barEntry) {
int barEntryY = (int) barEntry.getY();
return (String)barEntry.getData() + " " + "(" + String.valueOf(barEntryY) + ")";
}
});
barchart_type.setRenderer(new MyRenderer(barchart_type, barchart_type.getAnimator(), barchart_type.getViewPortHandler()));
Legend l_type = barchart_type.getLegend();
l_type.setCustom(legends_type);
l_type.setWordWrapEnabled(true);
l_type.setDrawInside(true);
piechart_defects.setData(data_defect);
piechart_defects.invalidate();
piechart_source.setData(data_source);
piechart_source.invalidate();
barchart_type.getAxisLeft().setEnabled(false);
barchart_type.setScaleEnabled(false);
barchart_type.getAxisRight().setEnabled(false);
barchart_type.getAxisRight().setDrawGridLines(false);
barchart_type.getXAxis().setDrawLabels(false);
barchart_type.getXAxis().setDrawGridLines(false);
barchart_type.getDescription().setEnabled(false);
barchart_type.getLegend().setEnabled(false);
barchart_type.setBorderColor(Color.BLACK);
barchart_type.setDrawBorders(false);
barchart_type.setData(data_type);
barchart_type.setMinimumHeight(arr_by_type.size()*250);
barchart_type.invalidate();
Log.e("INFO BAR", data_type.toString());
piechart_defects.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry e, Highlight h) {
String value = String.valueOf((int)h.getY());
String toShow = "";
if(h.getX() == 0){
toShow = " MAJOR \n" + value;
chartSelectedDefect = "MAJOR";
barchart_type.setData(data_type_MAJOR);
}else if(h.getX() == 1){
toShow = " MEDIUM \n" + value;
chartSelectedDefect = "MEDIUM";
barchart_type.setData(data_type_MEDIUM);
barchart_type.invalidate();
}else if(h.getX() == 2){
toShow = " MINOR \n" + value ;
chartSelectedDefect = "MINOR";
barchart_type.setData(data_type_MINOR);
}else if(h.getX() == 3){
toShow = " OTHER \n" + value;
chartSelectedDefect = "OTHER";
barchart_type.setData(data_type_OTHER);
How it appears when I show all:
I am using the below code to generate some Test Data which gets the job done. No problems here.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
System.out.println("\nCluster__________________________" + numCluster);
writeToFile("Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
System.out.println("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
System.out.println("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
writeToFile("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
System.out.println("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
private static void writeToFile(String data) throws IOException {
File file = new File("dbscript_output.sql");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data);
br.close();
fr.close();
}
}
Question: Is there a better way to achieve it? Does Java 7/8/11 has any better API to do it? I am open for any shorter/smarter way of doing it using Java. The sample shown here is just a few elements. I have 16 Entities for which I have to prepare Test Data and all of them are connected (related). Thanks.
UPDATE
Please allow me to reframe the question.
Is there any shorter/smarter way to achieve above using pure Core Java 1.8+ ? Where I can club (merge) 'for' loop and 'writeToFile'? (in one liner may be?) Appreciate all for your help.
As our colleague mentioned above you can use try with resources as below (so you dont have to close every input stream). You can also short/change nested for loops with streams but it isn't clearer solution and you have to improve it.
public class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
IntStream.range(0, totalCluster).forEach(numCluster->{
writeToFile("Cluster__________________________" + numCluster);
IntStream.range(0, totalAgency).forEach(numAgency->{
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
IntStream.range(0, totalProgramArea).forEach(numProgramArea->
IntStream.range(0,totalUsers).forEach(numUser->{
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}));
});
});
}
private static void writeToFile(String data) {
File file = new File("dbscript_output2.sql");
try(FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr)) {
br.write(data);
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It's better to only open the file once (as opposed to opening and closing it for each entry).
Also, you can use the try-with-resources statement to ensure that the output file is closed automatically.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
// try-with-resources statement
try (BufferedWriter br = new BufferedWriter(new FileWriter("dbscript_output.sql"))) {
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
writeOutput(br, "Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
writeOutput(br,"\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
writeOutput(br,"\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
writeOutput(br,"\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
}
private static void writeOutput(BufferedWriter br, String data) throws IOException {
System.out.println(data);
br.write(data);
}
}
In the alternative below the nested loops have been refactored into separate methods and the file is opened just once and closed once you're done with it. It's not shorter but perhaps a bit more readable. Anyway, hope this gives you some inspiration.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.stream.IntStream;
class GenerateTestData {
static int TOTAL_CLUSTER = 2;
static int TOTAL_AGENCY = TOTAL_CLUSTER * 2;
static int TOTAL_PROGRAM_AREA = TOTAL_AGENCY * 2;
static int TOTAL_USERS = TOTAL_PROGRAM_AREA * 2;
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
try (BufferedWriter br = new BufferedWriter(new FileWriter(outfile, true))) {
createClusters(str -> writeLine(br, str));
}
}
private static void writeLine(BufferedWriter writer, String data) {
try {
System.out.println(data);
writer.write(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void createClusters(Consumer<String> consumer) {
IntStream.range(1, TOTAL_CLUSTER).forEach(numCluster -> {
consumer.accept("Cluster__________________________" + numCluster);
createAgencies(consumer, numCluster);
});
}
private static void createAgencies(Consumer<String> consumer, int numCluster) {
IntStream.range(1, TOTAL_AGENCY).forEach(numAgency -> {
consumer.accept("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
createProgramAreas(consumer, numAgency);
});
}
private static void createProgramAreas(Consumer<String> consumer, int numAgency) {
IntStream.range(1, TOTAL_PROGRAM_AREA).forEach(numProgramArea -> {
consumer.accept("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
createUsers(consumer, numAgency, numProgramArea);
});
}
private static void createUsers(Consumer<String> consumer, int numAgency, int numProgramArea) {
IntStream.range(1, TOTAL_USERS).forEach(numUser -> {
consumer.accept("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea + "_User_" + numUser);
});
}
}
This is my BFS algorithm code.
I can calculate the shortest path distance, but somehow I am not able to display the shortest path.
Like for example, I calculated the shortest path from source to destination is 2. But i would like to also display the pathway. (PlaceA -> PlaceB -> PlaceC) for example.
May i know how do i display out the shortest path out using Java?
Please do help me! Thank you!
public static void main(String[] args) {
// TODO Auto-generated method stub
chooseNumOfVertices();
chooseNumOfEdges();
generateGraph();
in.close();
}
private static void generateGraph() {
int source = 0;
int destination = 0;
int edge = chooseEdge;
// TODO Auto-generated method stub
ArrayList<LinkedList<Integer>> graph = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < limit; i++) {
LinkedList<Integer> vertex = new LinkedList<Integer>();
vertex.add(i);
graph.add(vertex);
}
while (chooseEdge > 0) {
// Randomize the value
int value = new Random().nextInt(cityMapping.size());
int value2 = new Random().nextInt(cityMapping.size());
//
if (value != value2 && !graph.get(value).contains(value2) && !graph.get(value2).contains(value)) {
graph.get(value).add(value2);
graph.get(value2).add(value);
chooseEdge--;
}
}
// Printing out the Nodes
for (int i = 0; i < graph.size(); i++) {
// Return each LinkedList nodes
// System.out.println(graph.get(i));
for (int j = 0; j < graph.get(i).size(); j++) {
// Return each individual nodes inside LinkedList
for (Entry<Integer, String> entry : cityMapping.entrySet()) {
if (entry.getKey() == graph.get(i).get(j)) {
//System.out.print(graph.get(i).get(j) + "-> ");
System.out.print(graph.get(i).get(j) + ". " + entry.getValue() + " -> ");
}
}
}
System.out.println();
}
do {
for (
int i = 0; i < limit; i++) {
int[] newArray = new int[limit];
distance.add(newArray);
predecessor.add(newArray);
}
long time = System.nanoTime();
System.out.println("Searching BFS");
System.out.println("--------------------------------------------");
for (int i = 0; i < limit; i++) {
BFS(graph, i);
}
long CPUTime = (System.nanoTime() - time);
System.out.println("CPU Time for BFS for " + limit + "vertices and " + edge + "edges (in ns): " + CPUTime);
System.out.print("Enter -1 to exit! Enter source vertex (between 0 to " + (limit - 1) + ") : ");
source = in.nextInt();
if (source == -1) {
System.out.print("System terminating...");
break;
}
System.out.print("Enter destination vertex (between 0 to " + (limit - 1) + ") : ");
destination = in.nextInt();
System.out.println("Distance from " + source + " to " + destination + " is: " +
getDistance(source, destination));
System.out.println("The Predecessor of the path from " + source + " to " + destination + " is: "
+ getPredecessor(source, destination));
} while (source != -1);
}
private static void BFS(ArrayList<LinkedList<Integer>> graph, int i) {
// TODO Auto-generated method stub
boolean[] mark = new boolean[graph.size()];
Queue<Integer> L = new ArrayBlockingQueue<Integer>(graph.size()); //Queue
L.add(i);
mark[i] = true;
Arrays.fill(predecessor.get(i), -1);
Arrays.fill(distance.get(i), -1);
distance.get(i)[i] = 0;
while (!L.isEmpty()) {
int vertex = L.remove();
for (int i1 = 0; i1 < graph.get(vertex).size(); i1++) {
int v = graph.get(vertex).get(i1);
if (!mark[v]) {
mark[v] = true;
predecessor.get(i)[v] = vertex;
L.add(v);
distance.get(i)[v] = distance.get(i)[predecessor.get(i)[v]] + 1;
}
}
}
}
public static int getDistance(int start, int end) {
return (distance.get(start)[end]);
}
public static int getPredecessor(int start, int end) {
return (predecessor.get(start)[end]);
}
private static void chooseNumOfEdges() {
System.out.println("Please input the number of Edges:");
chooseEdge = in.nextInt();
}
// Number of Vertices
private static void chooseNumOfVertices() {
in = new Scanner(System.in);
System.out.println("Please input the number of Vertices:");
limit = in.nextInt();
// Read CSV
List<String[]> content = readCsvFile();
// Map each number to a city name
cityMapping = new HashMap<>();
for (int i = 0; i < limit; i++) {
cityMapping.put(i, content.get(i)[0]);
}
// System.out.println(cityMapping);
}
// Read CSV file
public static List<String[]> readCsvFile() {
String csvFile = "./Lab 4/country.csv";
BufferedReader br = null;
ArrayList<String> names = new ArrayList<String>();
List<String[]> content = new ArrayList<>();
String cvsSplitBy = ",";
try {
String line = "";
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
content.add(line.split(cvsSplitBy));
}
} catch (Exception e) {
e.printStackTrace();
}
Random r = new Random();
Collections.shuffle(content);
return content;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello I have been working on a program that predicts numbers. I have went through the code several times now and edited it. For some reason teamOneScored is ALWAYS higher than teamTwoScored. This does not make any sense to me.
What is the error that is occurring?
Here is my CompareEngine Class:
package compare;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import data.Main;
public class CompareEngine
{
public static void Comparison(int firstTeamTotal, int secondTeamTotal,
int[] firstPositionAmount, int[] secondPositionAmount, int[]
firstPosition, int[] secondPosition)
{
System.out.println(" Comparisons:");
System.out.println("----------------------------------------");
System.out.println(Main.firstTeam + " vs. " + Main.secondTeam);
System.out.println("----------------------------------------");
System.out.println(firstTeamTotal + " Total " + " " + secondTeamTotal);
System.out.println("");
System.out.println(firstPosition[0]-1+"-"+firstPosition[1]+"-"+firstPosition[2] + " Formation " + (secondPosition[0]-1) +"-"+secondPosition[1]+"-"+secondPosition[2]);
System.out.println("");
System.out.println(firstPosition[0] + " Defenders " + " " + secondPosition[0]);
System.out.println(firstPositionAmount[0] + " Defense Total " + " " + secondPositionAmount[0]);
System.out.println("");
System.out.println(firstPosition[1] + " Midfielders " + " " + secondPosition[1]);
System.out.println(firstPositionAmount[1] + " Midfield Total " + " " + secondPositionAmount[1]);
System.out.println("");
System.out.println(firstPosition[2] + " Attackers " + " " + secondPosition[2]);
System.out.println(firstPositionAmount[2] + " Attack Total " + " " + secondPositionAmount[2]);
}
public static void RunGame(int firstTeamTotal, int secondTeamTotal, int[] firstPositionAmount,
int[] secondPositionAmount, int[] firstPosition, int[] secondPosition) throws IOException
{
int depth;
System.out.println("What depth do you want to run?");
depth = Main.read.nextInt();
int firstShotCount = 0;
int secondShotCount = 0;
int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2;
int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2;
int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2;
int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2;
while(firstAttack*3 > secondDefense)
{
firstShotCount = firstShotCount + 1;
firstAttack = firstAttack - 5;
}
while(secondAttack*3 > firstDefense)
{
secondShotCount = secondShotCount + 1;
secondAttack = secondAttack - 5;
}
System.out.println(firstShotCount);
System.out.println(secondShotCount);
PossessionControl(Main.firstTeam, Main.secondTeam);
int[] teamOneScored = new int[99];
int[] teamTwoScored = new int[99];
int[] oneShotOn = new int[99];
int[] twoShotOn = new int[99];
int[] OnePossession = new int[99];
int[] TwoPossession = new int[99];
Random random = new Random();
for(int i = 0; i < depth; i++)
{
for(int x = 0; firstShotCount >= x; x++)
{
int shot = random.nextInt(10 - 1 + 1) + 1;
if (shot > 8)
{
teamOneScored[i] = teamOneScored[i] + 1;
}
if (shot > 4)
{
oneShotOn[i] = oneShotOn[i] + 1;
}
}
for(int y = 0; secondShotCount >= y; y++)
{
int shot = random.nextInt(10 - 1 + 1) + 1;
if (shot > 8)
{
teamTwoScored[i] = teamTwoScored[i] + 1;
}
if (shot > 4)
{
twoShotOn[i] = twoShotOn[i] + 1;
}
}
System.out.println(teamOneScored[i] + ":" + teamTwoScored[i]);
}
}
static File firstDataFile = new File("src/playerdata/" + Main.firstTeam);
static File secondDataFile = new File("src/playerdata/" + Main.secondTeam);
static int teamOnePossessionTotal = 0;
static int teamTwoPossessionTotal = 0;
public static void PossessionControl(String firstTeam, String secondTeam) throws IOException
{
BufferedReader br1 = new BufferedReader(new FileReader(firstDataFile));
String line = "";
for(int i = 1; i+1 < 13; i++)
{
line = br1.readLine();
teamOnePossessionTotal = teamOnePossessionTotal + PossessionStatTotal(line);
}
br1.close();
BufferedReader br2 = new BufferedReader(new FileReader(secondDataFile));
for(int i = 1; i+1 < 13; i++)
{
line = br2.readLine();
teamTwoPossessionTotal = teamTwoPossessionTotal + PossessionStatTotal(line);
}
br2.close();
}
public static int PossessionStatTotal(String line)
{
int value = 0;
String[] stats = line.split("-");
String position = stats[1];
if(!(position.equals("GK")))
{
String passing = stats[5];
String positioning = stats[7];
String ballControl = stats[9];
value = (int) ((int) (Integer.valueOf(passing)*.5) + Integer.valueOf(positioning)*.2 + Integer.valueOf(ballControl)*.1);
}
return value;
}
}
Here is my Main Class:
package data;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static String currentTeam;
public static void main(String[] args) throws IOException
{
compareTeams();
//setOveralls();
}
public static void setOveralls() throws IOException
{
Scanner read = new Scanner(System.in);
System.out.println("Which team do you like?");
currentTeam = read.nextLine();
read.close();
PlayerOverall.eraseOverallFile();
PlayerOverall.getPlayerInfo(13, currentTeam);
}
public static String firstTeam;
public static String secondTeam;
public static Scanner read = new Scanner(System.in);
public static void compareTeams() throws IOException
{
System.out.println("What is the first team?");
firstTeam = read.nextLine();
System.out.println("What is the second team?");
secondTeam = read.nextLine();
compare.CompareTeams.compare(firstTeam, secondTeam);
}
}
Here is the PlayerOverall Class, this just determines their Overall.
package data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PlayerOverall
{
//NOTE TO SELF -- CHANGE OUT OF HARD CODE VVVVVVVVVVV
static File dataFile = new File("src/playerdata/" + Main.currentTeam);
static File overallFile = new File("src/overalls/" + Main.currentTeam);
public static String getPlayerInfo(int numLine, String currentTeam) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(dataFile));
String line = "";
for(int i = 1; i+1 < numLine; i++)
{
line = br.readLine();
evaluatePlayer(line);
}
br.close();
return line;
}
public static void evaluatePlayer(String line) throws IOException
{
String[] stats = line.split("-");
String position = stats[1];
int overall = 0;
if(position.equals("GK"))
{
int height = Integer.parseInt(stats[2]);
int diving = Integer.parseInt(stats[3]);
int catching = Integer.parseInt(stats[4]);
int shooting = Integer.parseInt(stats[5]);
int reflexes = Integer.parseInt(stats[6]);
int positioning = Integer.parseInt(stats[7]);
overall = (int) ((int) ((int) ((int) ((int) ((int) (height*.05) + diving*.2) + catching*.2) + shooting*.1) + reflexes*.2) + positioning*.25);
setOverall(position, overall);
//OVERALL WORKS CORRECT NOW DO THE ADDITION OF OVERALL TO THE FILE!!
}
else
{
int speed = Integer.parseInt(stats[2]);
int acceleration = Integer.parseInt(stats[3]);
int distance = Integer.parseInt(stats[4]);
int passing = Integer.parseInt(stats[5]);
int shooting = Integer.parseInt(stats[6]);
int positioning = Integer.parseInt(stats[7]);
int defending = Integer.parseInt(stats[8]);
int ballControll = Integer.parseInt(stats[9]);
if(position.equals("LB") || position.equals("RB"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.1) + positioning*.15) + defending*.15) + ballControll*.1);
}
else if(position.equals("CB"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.095) + acceleration*.1) + distance*.1) + passing*.1) + shooting*.05) + positioning*.2) + defending*.3) + ballControll*.1);
}
else if(position.equals("CM"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.05) + acceleration*.05) + distance*.15) + passing*.2) + shooting*.1) + positioning*.2) + defending*.1) + ballControll*.1) + 10;
}
else if(position.equals("LM") || position.equals("RM"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.133) + positioning*.1) + defending*.033) + ballControll*.133) + 5;
}
else if(position.equals("ST"))
{
int stength = Integer.parseInt(stats[10]);
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.133) + acceleration*.133) + distance*.033) + passing*.05) + shooting*.225) + positioning*.225) + defending*.0) + ballControll*.1) + stength*.1) + 5;
}
setOverall(position, overall);
}
}
public static void setOverall(String position, int overall) throws IOException
{
try (FileWriter fw = new FileWriter(overallFile, true))
{
fw.append(position + "-" + overall +"\n");
}
}
public static void eraseOverallFile() throws IOException
{
FileWriter fw = new FileWriter(overallFile);
fw.write("");
fw.close();
}
}
The files I am getting for are just regular files. They look like this:
Lukas Hradecky-GK-63-81-81-74-89-82
Jetro Willems-LB-83-86-80-79-76-72-76-81
David Abraham-CB-76-83-68-74-70-76-80-61
Simon Falette-CB-60-71-77-57-50-74-84-56
Timmy Chandler-RB-80-76-83-74-68-71-77-74
Marco Fabian-CM-70-76-75-78-80-77-36-85
Jonathan De Guzman-CM-78-79-70-78-80-78-51-83
Mijat Gacinovic-RM-78-78-74-70-68-69-61-81
Ante Rebic-LM-76-79-71-62-78-72-40-75
Sebastien Haller-ST-75-79-73-64-77-77-35-79-91
Kevin Prince Boateng-ST-74-74-67-79-82-78-70-83-83
You can name this file whatever you like. Make another file in the appropriate location and it will generate everything else needed.
Thank you for your help!
I think you missed the minimal in [mcve].
TL;DR ... but spotted:
int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2;
int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2;
int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2;
int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2;
Indices are:
0 1
0 1
2 1
2 2
This seems inconsistent. Perhaps last should be a 1?
I am trying to find the max score from the array of objects. The code for that is everything below the int maxValue = -1; line of code. I am also trying to write that bands information to an external file:
import java.io.FileWriter;
public class App {
public static void main(String[] args) {
Bands[] bands = new Bands[5];
bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");
bands[0].compete();
bands[1].compete();
bands[2].compete();
bands[3].compete();
bands[4].compete();
for (int i = 0; i < 5; i++) {
String bandInfo = bands[i].getInfo();
System.out.println(bandInfo);
}
System.out.println("");
//DOESNT WORK BEYOND THIS POINT
int maxValue = -1;
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(bandInfo + "\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And then here is my Bands class code:
import java.util.Random;
public class Bands {
private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;
private int winningBand;
public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
this.singerName = singerName;
this.guitarName = guitarName;
this.bassistName = bassistName;
this.drummerName = drummerName;
this.bandName = bandName;
this.Hometown = Hometown;
this.income = income;
this.genre = genre;
this.score = -1;
this.winningBand = -1;
}
public void compete()
{
Random rand = new Random();
this.score = rand.nextInt(20);
}
public int getScore()
{
return this.score;
}
public String getInfo()
{
String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName +
", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " +
this.genre + ", Final Score: " + this.score;
return bandInfo;
}
}
As for your question about only printing band with highest score info:
Create a global variable (In this case I called it winningBand as an Integer)
Then edit your loop:
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
winningBand = i;
}
}
Then when you write to the file, only write the winningBand:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(band[winningBand].getInfo);
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
You are trying to find the highest score? Well in your code below
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
When you say .compete(), this does nothing. It assigns a random score in the Bands class. Instead it should look like this if you want to compare scores.
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
}
}
NOTE: You need to write a getScore() method in the band class that returns the score like the one below:
public Integer getScore(){
return score;
}
As for your question about writing to the file, this should work:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
for(int i = 0; i <= 4; i++){
fw.write(band[i].getInfo + "\n");
}
fw.close();
} catch (Exception e) {
e.printStackTrace();
}