Writing to File Error in Java - java

I am trying to write to a file (leaders.txt) and I am having an issue with the way the data I have calculated is showing in the file.
import java.io.*;
import java.util.*;
public class readStats {
public static int getStat(String letter, String stats) {
int count = stats.length() - stats.replace(letter, "").length();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
String hitsLeader = null;
String walksLeader = null;
String hitsByPitchLeader = null;
String strikeoutsLeader = null;
String battingAverageLeader = null;
int maxHits = 0;
int maxWalks = 0;
int maxHitsByPitch = 0;
int maxStrikeouts = 0;
int maxBa = 0;
java.io.File file = new java.io.File("stats.txt");
Scanner input = new Scanner(file);
//Find out number for each category
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(" ");
int hits = getStat("H", parts[1]);
int outs = getStat("O", parts[1]);
int walks = getStat("W", parts[1]);
int hitsByPitch = getStat("P", parts[1]);
int strikeouts = getStat("K", parts[1]);
int sacrifices = getStat("S", parts[1]);
int totalAtBats = hits + outs + strikeouts;
double ba = ((double)hits/(double)totalAtBats );
//System.out.println("Player " + parts[0]);
if (hits > maxHits) {
maxHits = hits;
hitsLeader = parts[0];
}
if (walks > maxWalks) {
maxWalks = walks;
walksLeader = parts[0];
}
if (hitsByPitch > maxHitsByPitch) {
maxHitsByPitch = hitsByPitch;
hitsByPitchLeader = parts[0];
}
if (strikeouts > maxStrikeouts) {
maxHits = hits;
strikeoutsLeader = parts[0];
}
if (ba > maxBa) {
maxHits = hits;
battingAverageLeader = parts[0];
}
//Create PrintWriter
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
// Print LEAGUE LEADERS to leaders.txt
output.println(parts[0]);
output.printf("BA: %.3f", ba);
output.println("H: " + hits);
output.println("BB: " + walks);
output.println("K: " + strikeouts);
output.println("HBP: " + hitsByPitch);
output.println("");
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
}
}
}
Output in leaders.txt
Pudge
BA: 0.450H: 9
BB: 2
K: 8
HBP: 1
LEAGUE LEADERS
BA: Pudge
H: Piazza
BB: Griffey
K: Pudge
HPB: Griffey
Stats.txt
Griffey HHOHOKWOHKSPOOWSHHWWWWWWW
Piazza OOHHHKPSOHOOHWWHOSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
Pudge HHHHKOOHHHSWWHHOPKKKKKKK
Desired Output
Griffey
BA: 0.462
H: 6
BB: 9
K: 2
HBP: 1
Piazza
BA: 0.833
H: 35
BB: 2
K: 1
HBP: 1
Pudge
BA: 0.450
H: 9
BB: 2
K: 8
HBP: 1
I need the output to display all three of the players that are associated in the file stats.txt, not just one.

Start the printer before the while loop and close it afterwards.
The league leaders should be printed only once.
Move those after the loop when you have the numbers of each player compared.
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
while (input.hasNextLine()) {
...
}
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
Edit: Add
output.println();
after
output.printf("BA: %.3f", ba);
printf doesn't start a new line.

Related

How do I validate text file contents in Java?

I'm creating a program which reads the contents of a .txt file, it validates and then outputs the contents of that file in a nice formatted table. My program currently reads the file and then outputs the content, I'm trying to implement the validation of said file content.
I'll now explain the way my program reads the file:
The .txt contents:
firstname lastname
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
The txt file contains data in this format:
{gamename} : {gamescore} : {minutesplayed}
To read the .txt I use:
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
To then split the data I use this for loop on each letter from a-to-g as shown below:
//~~~~a-line-split~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
To clarify by validation I need to inform the user if data is missing from a line for example if line one had:
gameone : {missing} : 1428
currently I have this simple if statement for each line:
if (bline.length < 3)
{
System.out.println("There is an error in row one!");
}
However I need to the program to know exactly where on each line the data is missing. Not just a generic response of:
System.out.println("There is an error in row one!");
But instead something along the lines of:
System.out.println("There is data missing, row: 1 column: 2");
Full code as requested:
package readfile;
import java.io.*;
import java.util.*;
public class readfile
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String FileN = " ";
String a = " ";
String b = " ";
String c = " ";
String d = " ";
String e = " ";
String f = " ";
String g = " ";
boolean fileExists = false;
File newFile = null;
while(!fileExists)
{
System.out.println("Enter the name of the file you want to open: ");
FileN = scan.nextLine();
newFile = new File(FileN);
fileExists = newFile.exists();
if (!fileExists)
{
System.out.println(FileN + " not found...");
}
}
try {
Scanner scan2;
scan = new Scanner(newFile);
}
catch(FileNotFoundException fnfe) {
System.out.println("sorry but the file doesn't seem to exist");
}
//++++++++++++++=FILE READ=++++++++++++++++++++
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
//+++++++++++++++ARRAYS FOR THE LINES+++++++++++++++++++
//~~~~A-LINE~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
//~~~~B-LINE~~~~//
String[] bline;
bline = b.split(":");
for (int i=0; i<bline.length; i++)
{
bline[i] = bline[i].trim();
//System.out.println(bline[i]);
}
//~~~~C-LINE~~~~//
String[] cline;
cline = c.split(":");
for (int i=0; i<cline.length; i++)
{
cline[i] = cline[i].trim();
//System.out.println(cline[i]);
}
//~~~~D-LINE~~~~//
String[] dline;
dline = d.split(":");
for (int i=0; i<dline.length; i++)
{
dline[i] = dline[i].trim();
//System.out.println(dline[i]);
}
//~~~~e-LINE~~~~//
String[] eline;
eline = e.split(":");
for (int i=0; i<eline.length; i++)
{
eline[i] = eline[i].trim();
//System.out.println(eline[i]);
}
//~~~~f-LINE~~~~//
String[] fline;
fline = f.split(":");
for (int i=0; i<fline.length; i++)
{
fline[i] = fline[i].trim();
//System.out.println(fline[i]);
}
//~~~~g-LINE~~~~//
String[] gline;
gline = g.split(":");
for (int i=0; i<gline.length; i++)
{
gline[i] = gline[i].trim();
//System.out.println(gline[i]);
}
String user = aline [0];
//~~~~~~~~~GAME NAMES~~~~~~~~~~~~~//
//GTA
String gameone = bline [0];
//MINECRAFT
String gametwo = cline [0];
//ASSASSIN'S CREED IV
String gamethree = dline [0];
//PAYDAY2
String gamefour = eline [0];
//WOLFENSTEIN
String gamefive = fline [0];
//FARCRY 4
String gamesix = gline [0];
//~~~~~~~~~~Achievement Score~~~~~~~~~~~~//
//GTA SCORE
String scoreone = bline [1];
//MINECRAFT SCORE
String scoretwo = cline [1];
//ASSASSIN'S CREED IV SCORE
String scorethree = dline [1];
//PAYDAY2 SCORE
String scorefour = eline [1];
//WOLFENSTEIN SCORE
String scorefive = fline [1];
//FARCRY 4 SCORE
String scoresix = gline [1];
//+++++++++++++++++++++TOTAL~~CALC++++++++++++++++++++++//
double totalcount = 79.566; // change to the amount played.
int totalhours = (int)totalcount;
int totalmin = (int)(totalcount*60)%60;
int totalsec = (int)(totalcount*(60*60))%60;
System.out.println("TOTAL TIME PLAYED:");
System.out.println(String.format("%s(hours) %s(minutes) %s(seconds)",
totalhours, totalmin, totalsec));
//~~~~~~~~~~Minutes Played~~~~~~~~~~~~//
//GTA min
String minone = bline [2];
//MINECRAFT min
String mintwo = cline [2];
//ASSASSIN'S CREED IV min
String minthree = dline [2];
//PAYDAY2 min
String minfour = eline [2];
//WOLFENSTEIN min
String minfive = fline [2];
//FARCRY 4 min
String minsix = gline [2];
//~~~~~~~~~GAMES TEST~~~~~~~~~~~~//
System.out.println("\nUSER: "+user);
System.out.println("\nDATA: ");
System.out.println("1: "+gameone+" | score: "+scoreone+"
| minutes played: "+minone);
System.out.println("2: "+gametwo+" | score: "+scoretwo+"
| minutes played: "+mintwo);
System.out.println("3: "+gamethree+" | score: "+scorethree+"
| minutes played: "+minthree);
System.out.println("4: "+gamefour+" | score:
"+scorefour+" | minutes played: "+minfour);
System.out.println("5: "+gamefive+" | score: "+scorefive+"
| minutes played: "+minfive);
System.out.println("6: "+gamesix+" | score: "+scoresix+"
| minutes played: "+minsix);
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two
column "+(i+1));
}
}
}
}
}
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two column "+(i+1));
}
}
}
Didn't test this but it should work
EDIT:
Looking at your full code bline[2], cline[2]... and so on will give you an Index Out of bounds exception if those values are missing from the file in the first place so before making that call you should do a check first you can create a static method to do the check
public static String getAtIndex(String[] array, int indexToCkeck){
if(indexToCkeck >=array.length){
return "";
}
else{
return array[indexToCkeck];
}
}
So instead of doing bline[2], cline[2] ... use readfile.getAtIndex(bline, 2) so this way if the info is missing it will return an empty string
Also not tested, should be fine though
Use a well tested library like supercsv or any other. This will save you some hours as soon as your text format gets more complex. It also provides a good set of build-in data types to be used to validate each single column of your data. Also you can map the data directly to a POJO which can be handy in some situations.
To load just each row into a map you could do the following:
Prepare your file in stack47220687.txt:
Gamename: Gamescore: Minutestoplay
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
And use something like this
package stack47220687;
import java.io.FileReader;
import java.util.Map;
import org.junit.Test;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.prefs.CsvPreference;
public class HowToReadACSVFile {
private static final CsvPreference COLON_DELIMITED = new CsvPreference.Builder('"', ':', "\n").build();
private static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // gamename
new NotNull(), // gamescore
new NotNull(), // minutestoplay
};
return processors;
}
#Test
public void read() throws Exception {
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(
Thread.currentThread().getContextClassLoader().getResource("stack47220687.txt").getPath()),
COLON_DELIMITED);
// the header columns are used as the keys to the Map
final String[] header = mapReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
Map<String, Object> oneRecordInAMap;
while ((oneRecordInAMap = mapReader.read(header, processors)) != null) {
System.out.println(String.format("lineNo=%s, rowNo=%s, this line stored in a map=%s",
mapReader.getLineNumber(), mapReader.getRowNumber(), oneRecordInAMap));
/**
* oneRecordInAMap.get("Gamescore");
*/
}
} finally {
if (mapReader != null) {
mapReader.close();
}
}
}
}
works with super-csv 2.4.0
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>
and will print
lineNo=2, rowNo=2, this line stored in a map={ Gamescore= 120 , Gamename=Gameone , Minutestoplay= 1428 }
lineNo=3, rowNo=3, this line stored in a map={ Gamescore= 20 , Gamename=Gametwo , Minutestoplay= 10 }
lineNo=4, rowNo=4, this line stored in a map={ Gamescore= 90 , Gamename=Gamethree , Minutestoplay= 800 }
lineNo=5, rowNo=5, this line stored in a map={ Gamescore= 190 , Gamename=Gamefour , Minutestoplay= 2001 }
lineNo=6, rowNo=6, this line stored in a map={ Gamescore= 25 , Gamename=Gamefive , Minutestoplay= 80 }
lineNo=7, rowNo=7, this line stored in a map={ Gamescore= 55 , Gamename=Gamesix , Minutestoplay= 862}
It will also provide meaningful error messages if your format is not correct.

multiple String location find using a key in a tag

I want to parse an input eg: GH123FG12B1A58 .
'GH' / 'FG' / 'A' / 'B' will be there in all the tags in same order but different position . eg: GH14555523FG1555552B55551A55558
Need to find the value after every keys
I see this can be done by using patter , get start & end index ? Is there any other way to acomplish this ?
import java.util.Scanner;
public class Shipparse {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner Iname = new Scanner(System.in);
System.out.println("Enter the invoice :");
String Maintag = Iname.nextLine();
String GH = "GH";
String FG = "FG";
String AB = "AB";
String B = "B";
String A = "A";
int cus = Maintag.indexOf(GH);
int cys = Maintag.indexOf(FG);
int ats = Maintag.indexOf(AB);
int ss = Maintag.indexOf(B);
int se = Maintag.indexOf(A);
int tlength = Maintag.length();
StringBuilder str = new StringBuilder(Maintag);
String cnum;
if ( ats == -1) {
cnum = str.substring((cus +2) , cys);
System.out.println("Customer :" + cnum);
String cyn = str.substring((cys + 2), ss);
System.out.println("Agent :" + cyn);
} else {
cnum = str.substring((cus +2) , ats);
System.out.println("Customer :" + cnum);
String cyn = str.substring((ats + 2), ss);
System.out.println("Company:" + cyn);
}
String spoint = str.substring((ss +1) , se);
System.out.println("TYPE NUM:" + spoint);
String send = str.substring((se +1) , tlength);
System.out.println("FIELD NUM :" + send);
}
}

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive

import java.util.Random;
import java.util.StringTokenizer;
public class FortuneCookie {
private String subjList;
private String objList;
private String verbList;
private int sWords = 0;
private int oWords = 0;
private int vWords = 0;
private Random random = new Random();
public FortuneCookie() {
subjList = "i#You#He#She#It#They";
objList = "me#you#him#her#it#them";
verbList = "hate#love#deny#find#hear#forgive#hurt#win#teach";
}
public void setSubject(String subj) {
subjList = subj;
}
public void setObjectList(String obj) {
objList = obj;
}
public void setVerbList(String verb) {
verbList = verb;
}
public String genFortuneMsg() {
String v = " ";
String o = " ";
String s = " ";
StringTokenizer st1 = new StringTokenizer(subjList, "#");
StringTokenizer st2 = new StringTokenizer(objList, "#");
StringTokenizer st3 = new StringTokenizer(verbList, "#");
while (st1.hasMoreTokens()) {
s = st1.nextToken();
sWords = st1.countTokens();
int no = random.nextInt(sWords);
if (no == sWords) {
break;
}
}
while (st2.hasMoreTokens()) {
o = st2.nextToken();
oWords = st2.countTokens();
int no2 = random.nextInt(oWords);
if (no2 == oWords) {
break;
}
}
while (st3.hasMoreTokens()) {
v = st3.nextToken();
vWords = st3.countTokens();
int no3 = random.nextInt(vWords);
if (no3 == vWords) {
break;
}
}
String gen = s + " " + v + " " + o;
return gen;
}
public void print() {
System.out.println("Tokens");
System.out.println("Subject List:" + subjList + " count = " + sWords);
System.out.println("verb List:" + verbList + " count = " + vWords);
System.out.println("object List:" + objList + " count = " + oWords);
}
}
Exception in thread "main" java.lang.IllegalArgumentException: bound
must be positive at java.util.Random.nextInt(Random.java:388) at
FortuneCookie.genFortuneMsg(FortuneCookie.java:42) at
FortuneCookieTest.main(FortuneCookieTest.java:6)
Your case is not negative it is zero.
From the docs of countToken method
/**
* Calculates the number of times that this tokenizer's
* <code>nextToken</code> method can be called before it generates an
* exception. The current position is not advanced.
*
In a while loop when your count token return zero, you run into an exception. Well that error message should be reformatted to negative or zero.
Add 1 to your result or check for zero. Should work.

Error message for StorageResource type

I've been trying to work on this problem for a while now but to no avail. When I run the code I get this error message: incompatible types: edu.duke.StorageResource cannot be converted to java.lang.String on line String geneList = FMG.storeAll(dna);. Does this mean I'm trying to make edu.duke object work with a java.lang.String type object? What would we go about resolving this issue?
Here's my code so far:
package coursera_java_duke;
import java.io.*;
import edu.duke.FileResource;
import edu.duke.StorageResource;
import edu.duke.DirectoryResource;
public class FindMultiGenes5 {
public int findStopIndex(String dna, int index) {
int stop1 = dna.indexOf("TGA", index);
if (stop1 == -1 || (stop1 - index) % 3 != 0) {
stop1 = dna.length();
}
int stop2 = dna.indexOf("TAA", index);
if (stop2 == -1 || (stop2 - index) % 3 != 0) {
stop2 = dna.length();
}
int stop3 = dna.indexOf("TAG", index);
if (stop3 == -1 || (stop3 - index) % 3 != 0) {
stop3 = dna.length();
}
return Math.min(stop1, Math.min(stop2, stop3));
}
public StorageResource storeAll(String dna) {
//CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCAdna = "CATGTAATAGATGAATGACTGATAGATATGCTTGTATGCTATGAAAATGTGAAATGACCCA";
String geneAL = new String();
String sequence = dna.toUpperCase();
StorageResource store = new StorageResource();
int index = 0;
while (true) {
index = sequence.indexOf("ATG", index);
if (index == -1)
break;
int stop = findStopIndex(sequence, index + 3);
if (stop != sequence.length()) {
String gene = dna.substring(index, stop + 3);
store.add(gene);
//index = sequence.substring(index, stop + 3).length();
index = stop + 3; // start at the end of the stop codon
}else{ index = index + 3;
}
}
return store;//System.out.println(sequence);
}
public void testStorageFinder() {
DirectoryResource dr = new DirectoryResource();
StorageResource dnaStore = new StorageResource();
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
String s = fr.asString();
dnaStore = storeAll(s);
printGenes(dnaStore);
}
System.out.println("size = " + dnaStore.size());
}
public String readStrFromFile(){
FileResource readFile = new FileResource();
String DNA = readFile.asString();
//System.out.println("DNA: " + DNA);
return DNA;
}//end readStrFromFile() method;
public float calCGRatio(String gene){
gene = gene.toUpperCase();
int len = gene.length();
int CGCount = 0;
for(int i=0; i<len; i++){
if(gene.charAt(i) == 'C' || gene.charAt(i) == 'G')
CGCount++;
}//end for loop
System.out.println("CGCount " + CGCount + " Length: " + len + " Ratio: " + (float)CGCount/len);
return (float)CGCount/len;
}//end of calCGRatio() method;
public void printGenes(StorageResource sr){
//create a FindMultiGenesFile object FMG
FindMultiGenes5 FMG = new FindMultiGenes5();
//read a DNA sequence from file
String dna = FMG.readStrFromFile();
String geneList = FMG.storeAll(dna);
//store all genes into a document
StorageResource dnaStore = new StorageResource();
System.out.println("\n There are " + geneList.size() + " genes. ");
int longerthan60 = 0;
int CGGreaterthan35 = 0;
for(int i=0; i<geneList.size(); i++){
if(!dnaStore.contains(geneList.get(i)))
dnaStore.add(geneList.get(i));
if(geneList.get(i).length() > 60) longerthan60++;
if(FMG.calCGRatio(geneList.get(i)) > 0.35) CGGreaterthan35++;
}
System.out.println("dnaStore.size: " + dnaStore.size());
System.out.println("\n There are " + dnaStore.size() + " genes. ");
System.out.println("There are " + longerthan60 + " genes longer than 60.");
System.out.println("There are " + CGGreaterthan35 + " genes with CG ratio greater than 0.35.");
}//end main();
}
I found your post as I am also doing a similar course at Duke using those edu.duke libraries.
When I get that error message it is because I'm using the wrong method to access it.
Try FMD.data() to get an iterable of all of the gene strings.

Using scanner to read file and group data

I'm using scanner to read file and group data , ive done some work but facing problem when im tring to deal with
The data sets is this.
You can see a example here, that explain everything.
What i ve done is this :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class TextScanner {
// static File f = new File("nrp1.txt");
public static void main(String[] args) throws FileNotFoundException {
TextScanner ts = new TextScanner();
ts.readfile();
}
public void readfile() throws FileNotFoundException {
FileInputStream fis = new FileInputStream("nrp1.txt");
Scanner scanner = new Scanner(fis);
int lineCount = 0;
String firstline = scanner.nextLine();
String secondline = scanner.nextLine();
String thirdline = scanner.nextLine();
String fourthline = scanner.nextLine();
String fifthline = scanner.nextLine();
String sixthline = scanner.nextLine();
String seventhline = scanner.nextLine();
String eighththline = scanner.nextLine();
List<Integer> intArrRIDA = new ArrayList<Integer>();
List<Integer> intArrRIDB = new ArrayList<Integer>();
int[] intRIDA = new int[Integer.parseInt(eighththline)];
int[] intRIDB = new int[Integer.parseInt(eighththline)];
List<Integer> intArrPOC = new ArrayList<Integer>();
List<Integer> intArrNORBC = new ArrayList<Integer>();
List<Integer> intArrRL = new ArrayList<Integer>();
String NoC="";
// COR arrays
thirdline.trim();
String[] CoR1 = thirdline.split(" ");
int[] intCoR1 = new int[CoR1.length];
for (int i = 0; i < intCoR1.length; i++) {
intCoR1[i] = Integer.parseInt(CoR1[i]);
}
fifthline.trim();
String[] CoR2 = fifthline.split(" ");
int[] intCoR2 = new int[CoR2.length];
for (int i = 0; i < intCoR2.length; i++) {
intCoR2[i] = Integer.parseInt(CoR2[i]);
}
seventhline.trim();
String[] CoR3 = seventhline.split(" ");
int[] intCoR3 = new int[CoR3.length];
for (int i = 0; i < intCoR3.length; i++) {
intCoR3[i] = Integer.parseInt(CoR3[i]);
}
while (scanner.hasNextLine()) {
lineCount++;
String line = scanner.nextLine().trim();
if (lineCount >= 1 && lineCount <= Integer.parseInt(eighththline)) {
// System.out.println("line: " + line);
String[] RID = line.split(" ");
for (int i = 0; i < 1; i++) {
intArrRIDA.add(Integer.parseInt(RID[0]));
intArrRIDB.add(Integer.parseInt(RID[1]));
// intRIDA[i] = Integer.parseInt(RID[0]);
// intRIDB[i] = Integer.parseInt(RID[1]);
// System.out.println("Id of RequirementA : " + intRIDA[i]);
// System.out.println("Id of RequirementB : " + intRIDB[i]);
}
}
if (lineCount == Integer.parseInt(eighththline)) {
NoC = scanner.nextLine();
}
//System.out.println("Number of Customer : " + NoC);
if (lineCount > Integer.parseInt(eighththline)) {
// System.out.println("line: " + line);
String[] Customers = line.split(" ");
System.out.println("Details of Customer : " +Arrays.toString(Customers) );
intArrPOC.add(Integer.parseInt(Customers[0]));
intArrNORBC.add(Integer.parseInt(Customers[1]));
for (int i = 0; i < 6; i++) {
intArrRL.add(Integer.parseInt(Customers[2]));
if (Customers[3] != null) {
intArrRL.add(Integer.parseInt(Customers[3]));
}
else if (Customers[4] != null) {
intArrRL.add(Integer.parseInt(Customers[4]));
}
else if (Customers[5] != null) {
intArrRL.add(Integer.parseInt(Customers[5]));
}
else if (Customers[6] != null) {
intArrRL.add(Integer.parseInt(Customers[6]));
}
else
continue;
}
}
}
System.out.println("Level of requirements, t: " + firstline);
System.out.println("Number of requirements in Level 1: " + secondline);
System.out.println("Costs of requirements in Level 1 : "
+ Arrays.toString(intCoR1));
System.out.println("Number of requirements in Level 2: " + fourthline);
System.out.println("Costs of requirements in Level 2 : "
+ Arrays.toString(intCoR2));
System.out.println("Number of requirements in Level 3: " + sixthline);
System.out.println("Costs of requirements in Level 3 : "
+ Arrays.toString(intCoR3));
System.out.println("Number of dependencies: " + eighththline);
// System.out.println("Id of RequirementA : " +
// Arrays.toString(intRIDA));
// System.out.println("Id of RequirementB : " +
// Arrays.toString(intRIDB));
System.out.println("Id of RequirementA : " + intArrRIDA);
System.out.println("Id of RequirementB : " + intArrRIDB);
System.out.println("Number of Customer : " + NoC);
System.out.println("Profit of Customer : " + intArrPOC);
System.out.println("Number of requests by Customer: " + intArrNORBC);
System.out.println("Requirements List : " + intArrRL);
}
private boolean isNumeric(String number) {
try {
Integer.parseInt(number);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
But as you can see :
for (int i = 0; i < 6; i++) {
intArrRL.add(Integer.parseInt(Customers[2]));
if (Customers[3] != null) {
intArrRL.add(Integer.parseInt(Customers[3]));
}
else if (Customers[4] != null) {
intArrRL.add(Integer.parseInt(Customers[4]));
}
else if (Customers[5] != null) {
intArrRL.add(Integer.parseInt(Customers[5]));
}
else if (Customers[6] != null) {
intArrRL.add(Integer.parseInt(Customers[6]));
}
else
continue;
}
This part is not correct ,and i need them to linked with Profit of Customer and Number of requests by Customer and when i implement further stuffs, i may able to find the corresponding Requirements List and the number of request by Profit of Customer...
I haven't started doing this method yet but that would be great if you can help me with this as well!
Thanks!

Categories

Resources