I'm getting a NullPointerException error in Eclipse. Code as it stands right now:
Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System. * ;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib() {}
public MadLib(String fileName) {
//load stuff
try {
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e) {
out.println("Houston we have a problem!");
}
}
public void loadNouns() {
nouns = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("nouns.dat");
while (chopper.hasNext()) {
nouns.add(chopper.next());
}
chopper.close();
out.println(nouns);
}
catch(Exception e) {
out.println("Will");
}
}
public void loadVerbs() {
verbs = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("verbs.dat");
while (chopper.hasNext()) {
verbs.add(chopper.next());
}
chopper.close();
}
catch(Exception e) {
out.println("run");
}
}
public void loadAdjectives() {
adjectives = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("adjectives.dat");
while (chopper.hasNext()) {
adjectives.add(chopper.next());
}
chopper.close();
}
catch(Exception e) {}
}
public String getRandomVerb() {
String verb = "";
int num = 0;
num = (int)(Math.random() * verbs.size());
verb = verbs.get(num);
return verb;
}
public String getRandomNoun() {
String noun = "";
int num = 0;
num = (int)(Math.random() * nouns.size());
noun = nouns.get(num);
return noun;
}
public String getRandomAdjective() {
String adj = "";
int num = 0;
num = (int)(Math.random() * adjectives.size());
adj = adjectives.get(num);
return adj;
}
public String toString() {
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
Eclipse is pointing to the issue occurring at the linenum = (int)(Math.random()*nouns.size()); but this seems to not make much sense to me.
I have the private ArrayList<String> initialized at the method loadNouns. I origianlly had ArrayList<String> nouns initialized at getRandomNoun(), but that threw a different error, so I was advised to move the initialization statement to the loadNouns method.
Runner Class:
import static java.lang.System.*;
public class Lab16d
public static void main( String args[] ) {
//make a new MadLib
MadLib fun = new MadLib();
out.println(fun);
}
Update:
The real issue appears to be that ArrayList<String> nouns never is "loaded up" with the separate strings which are supposed to be scanned in from the nouns.dat file
Update 2:
Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System. * ;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib() {
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName) {
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try {
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e) {
out.println("Houston we have a problem!");
}
}
public void loadNouns() {
nouns = new ArrayList < String > ();
try {
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File("nouns.dat"));
//chopper.nextLine();
while (chopper.hasNext()) {
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e) {
out.println("Will");
}
}
public void loadVerbs() {
verbs = new ArrayList < String > ();
try {
Scanner chopper = new Scanner(new File("verbs.dat"));
while (chopper.hasNext()) {
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e) {
out.println("run");
}
}
public void loadAdjectives() {
adjectives = new ArrayList < String > ();
try {
Scanner chopper = new Scanner(new File("adjectives.dat"));
while (chopper.hasNext()) {
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e) {}
}
public String getRandomVerb() {
String verb = "";
int num = 0;
num = (int)(Math.random() * (verbs.size() - 1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun() {
String noun = "";
int num = 0;
if (nouns == null) {
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size() - 1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective() {
String adj = "";
int num = 0;
num = (int)(Math.random() * (adjectives.size() - 1));
adj = adjectives.get(num);
return adj;
}
public String toString() {
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
You are creating an instance of MadLib, then printing the object in a println in your Runner class...
//make a new MadLib
MadLib fun = new MadLib();
out.println(fun);
The out.println calls the toString() method you overrode in MadLib...
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
Your MadLib object has 3 ArrayLists you never initialized, so they are null...
private ArrayList<String> verbs;
private ArrayList<String> nouns;
private ArrayList<String> adjectives
The easiest way to fix the NullPointerException is to initialize the variables....
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
However, what I really think you want to do is load all the nouns, verbs and adjectives when your object is constructed so your toString actually prints something useful. I'd add this to your constructor as well...
public MadLib() {
loadNouns();
loadVerbs();
loadAdjectives();
}
Edit: Your getRandom methods need to check if the list is empty to avoid the IndexOutOfBounds exception as well...
public String getRandomVerb() {
String verb = "";
if (!verbs.isEmpty()) {
int num = (int) (Math.random() * verbs.size() - 1);
verb = verbs.get(num);
}
return verb;
}
public String getRandomNoun() {
String noun = "";
if (!nouns.isEmpty()) {
int num = (int) (Math.random() * nouns.size() - 1);
noun = nouns.get(num);
}
return noun;
}
public String getRandomAdjective() {
String adj = "";
if (!adjectives.isEmpty()) {
int num = (int) (Math.random() * adjectives.size());
adj = adjectives.get(num);
}
return adj;
}
Hope that helps
Related
I was wondering is there a way to use other class variable in #Override?
Here is my first class. I've tried to use setters & getters, but still receiving an error:
public class Darbuotojas {
String dVardas;
String dPavarde;
int dAmzius;
int dPatirtis;
Programuotojas programuotojas = new Programuotojas();
String check = programuotojas.getDarboKalba();
Darbuotojas() { }
public Darbuotojas(String dVardas, String dPavarde, int dAmzius, int dPatirtis) {
this.dVardas = dVardas;
this.dPavarde = dPavarde;
this.dAmzius = dAmzius;
this.dPatirtis = dPatirtis;
}
#Override
public String toString() {
return dVardas + " " + dPavarde + " " + dAmzius + " " + dPatirtis + " " + check;
}}
And here is my another class:
public class Programuotojas extends Darbuotojas {
Programuotojas(){}
public String getDarboKalba() {
return darboKalba;
}
public void setDarboKalba(String darboKalba) {
this.darboKalba = darboKalba;
}
public String darboKalba;
public Programuotojas(String dVardas, String dPavarde, int dAmzius, int dPatirtis, String darboKalba) {
super(dVardas, dPavarde, dAmzius, dPatirtis);
this.darboKalba = darboKalba;
}
As I see I formulated bad and not understandable question for you guys. I will try to explain. I have father class Darbuotojas with 4 parameters, in subclass Programuotojas I add one more parameter - darboKalba. So what I want from Override to return these 4 paremeters from Darbuotojas + one from Programuotojas.
// Darbuotoju valdymas prasideda //
public void darbuotojuVald() {
System.out.println("---- Darbuotoju valdymas ----");
System.out.println("[1] Prideti nauja darbuotoja");
System.out.println("[2] Pasalinti darbuotoja");
System.out.println("[3] Atnaujinti darbuotoja");
System.out.println("[4] Pamatyti darbuotoju sarasa");
System.out.println("[5] Gauti informacija apie pasirinkta darbuotoja");
Scanner SI = new Scanner(System.in);
int vartotojoIvestis = Integer.parseInt(SI.nextLine());
if (vartotojoIvestis == 1) {
System.out.println("---- Prideti nauja darbuotoja ----");
System.out.println("[1] Programuotoja");
System.out.println("[2] kita");
int vartotojoIvestis2 = Integer.parseInt(SI.nextLine());
if (vartotojoIvestis2 == 1) {
pridetiDarbuotojaProgramuotoja();
} else {
System.out.println("In progress....");
}
} else if (vartotojoIvestis == 4) {
bendrasDarbuotojuSarasas();
}
}
// Programuotojo pridejimas prasideda //
private void pridetiDarbuotojaProgramuotoja() {
System.out.println("---- Pridedamas naujas programuotojas ----");
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, patirti, programavimo kalba");
Scanner SI = new Scanner(System.in);
String[] iveda = SI.nextLine().split(" ");
programuotojas.add(new Programuotojas(iveda[0], iveda[1], Integer.parseInt(iveda[2]), Integer.parseInt(iveda[3]), iveda[4]));
System.out.println("---- Sekmingai pridetas naujas darbuotojas ----");
System.out.println("Vardas: " + iveda[0]
+ ",pavarde: " + iveda[1]
+ ",amzius: " + iveda[2]
+ ",patirtis: " + iveda[3]
+ ",programavimo kalba: " + iveda[4]);
darbuotojuSarasas.clear();
darbuotojuSarasas.addAll(programuotojas);
darbuotojuVald();
}
private void bendrasDarbuotojuSarasas() {
System.out.println("---- Visas darbuotoju sarasas ----");
for(int i = 0; i < darbuotojuSarasas.size(); i++) {
System.out.println("ID " + i + " " + darbuotojuSarasas.get(i));
}
darbuotojuVald();
}
Reflection can be tricky, and I can't guarantee it'll work for all circumstances. This worked well enough for me.
package quicktest;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Brenden
*/
public class FieldDumpTest {
public static void main( String[] args ) {
System.out.println( new FieldDump3() );
}
public final String topTestString = "This is a test.";
protected int topInt = 11;
float topFloat = 123.456f;
private short topShort = Short.MAX_VALUE;
#Override
public String toString() {
StringBuilder str = new StringBuilder();
Class<?> type = this.getClass();
do {
str.append( type.getName() );
str.append( " {" );
Field[] fields = type.getDeclaredFields();
for( int i = 0; i < fields.length; i++ ) {
Field field = fields[i];
str.append( field.getName() );
str.append( ":" );
try {
str.append( field.get( this ) );
} catch( IllegalAccessException | IllegalArgumentException ex ) {
str.append( "<NO ACCESS>" );
}
str.append( ", " );
}
str.append( "} " );
type = type.getSuperclass();
} while( type != null );
return str.toString();
}
}
class FieldDump2 extends FieldDumpTest {
private String test = "testtest";
}
class FieldDump3 extends FieldDump2 {
int ten = 10;
protected double fortytwo = 42.0;
}
Output:
run:
quicktest.FieldDump3 {ten:10, fortytwo:42.0, } quicktest.FieldDump2 {test:<NO ACCESS>, } quicktest.FieldDumpTest {topTestString:This is a test., topInt:11, topFloat:123.456, topShort:32767, } java.lang.Object {}
BUILD SUCCESSFUL (total time: 0 seconds)
I have a file that contains more than one value in one column. I was trying to read this file using java with this code:
ArrayList<String> linesList1 = new ArrayList<>();
ArrayList<String> roadlinkid = new ArrayList<>();
ArrayList<String> road_name_orignal = new ArrayList<>();
ArrayList<String> road_name_copy = new ArrayList<>();
ArrayList<String[]> networkmember_href = new ArrayList<>();
ArrayList<String> road_fid = new ArrayList<>();
// Input of file which needs to be parsed
String csvFile1 = "RoadData.csv";
BufferedReader csvReader1;
// Data split by ',' in CSV file
String csvSplitBy = ",";
try {
String line;
csvReader1 = new BufferedReader(new FileReader(csvFile1));
while ((line = csvReader1.readLine()) !=null) {
linesList1.add(line);
}
csvReader1.close();
}
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < linesList1.size(); i++) {
String[] data = linesList1.get(i).split(csvSplitBy);
road_fid.add( data[1]);
road_name_orignal.add( data[9]);
if (data[9].contains("{")) {
String[] xy = data[9].replaceAll("\\{|\\}", "").split(",");
int leng = xy.length;
String[] networkmember = new String [leng];
for ( int n = 0 ; n < leng ; n++) {
networkmember[n] = xy [n];
}
networkmember_href.add(networkmember);
}
}
This code works well, but the problem is that the code deals with each value in the column as a separate column. Therefore, it returns wrong data.
Files:
http://s000.tinyupload.com/?file_id=47090134488569683648
The idea is Finding the road name from RoadData.csv and write it in RoadLink.csv by comparing road_fid in RoadData.csv and roadlink_fid in RoadLink.csv. Unfortunately, I could find a way to deal with a column with multi-values. Any advice, please.
Thanks in advance.
Below is some code to parse the file, you can add additional processing to parse the fields that have lists in them or to combine the lists like changedate and reasonforchange into a list of Objects containing both pieces of data. For example a List<ChangeInfo> where ChangeInfo holds both the changedate and reasonforchange.
I still would recommend using a csv parser but this code should work well enough for this specific use case. Test thoroughly..
Main:
public static void main(String[] args){
List<RoadLinkRecord> records = parse("path\\to\\RoadLink.csv");
// display all the records
for (RoadLinkRecord record : records) {
System.out.println(record);
}
}
CSV Parsing:
private static final Pattern csvFieldPattern =
Pattern.compile("(?<=[$,])(\"(\"\"|[^\"])*\"|[^,]*)");
/** This parse method requires the CSV file to have a header row */
public static List<RoadLinkRecord> parse(String csvFilePath) {
// TODO accept Reader or maybe InputStream rather than file path
File f = new File(csvFilePath);
List<RoadLinkRecord> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f));) {
// get the header fields
String line = br.readLine();
List<String> headers = new ArrayList<>();
{
Matcher matcher = csvFieldPattern.matcher(line);
while (matcher.find())
headers.add(matcher.group());
}
// iterate through record fields
int recordNum = 0;
while ((line = br.readLine()) != null) {
recordNum++;
// allocate array to hold the fields
String[] fields = new String[headers.size()];
// use matcher to get each of the fields
Matcher matcher = csvFieldPattern.matcher(line);
for (int i = 0; i < headers.size(); i++) {
if (!matcher.find()) {
throw new IllegalArgumentException(
"Couldn't find field '" + headers.get(i) + "' for record " + recordNum);
}
fields[i] = matcher.group();
}
if (matcher.find()) {
throw new IllegalArgumentException("Found excess fields in record " + recordNum);
}
// add the record from this line
records.add(new RoadLinkRecord(recordNum, fields));
}
} catch (IOException e) {
// TODO trouble reading the file
} catch (IllegalArgumentException e) {
// TODO error while parsing the file
}
return records;
}
Data Container:
public class RoadLinkRecord {
private final int recordNumber;
private final String roadlink_fid;
private final String version;
private final String versiondate;
private final String changedate;
private final String reasonforchange;
private final String descriptivegroup;
private final String descriptiveterm;
private final String natureofroad;
private final String length;
private final String directednode_href;
private final String directednode_orientation;
private final String directednode_gradeseparation;
private final String referencetotopographicarea_href;
private final String theme;
private final String filename;
private final String wkb_geometry;
private final String roadnumber;
private final String dftname;
private final String fid;
private final String roadname;
public RoadLinkRecord(final int recordNumber, final String[] csvFields) {
if (csvFields.length != 20) {
throw new IllegalArgumentException(
"Wrong number of fields for a RoadLinkRecord! Expected 20, found "
+ csvFields.length);
}
this.recordNumber = recordNumber;
this.roadlink_fid = processStringField(csvFields[0]);
this.version = processStringField(csvFields[1]);
this.versiondate = processStringField(csvFields[2]);
this.changedate = processStringField(csvFields[3]);
this.reasonforchange = processStringField(csvFields[4]);
this.descriptivegroup = processStringField(csvFields[5]);
this.descriptiveterm = processStringField(csvFields[6]);
this.natureofroad = processStringField(csvFields[7]);
this.length = processStringField(csvFields[8]);
this.directednode_href = processStringField(csvFields[9]);
this.directednode_orientation = processStringField(csvFields[10]);
this.directednode_gradeseparation = processStringField(csvFields[11]);
this.referencetotopographicarea_href = processStringField(csvFields[12]);
this.theme = processStringField(csvFields[13]);
this.filename = processStringField(csvFields[14]);
this.wkb_geometry = processStringField(csvFields[15]);
this.roadnumber = processStringField(csvFields[16]);
this.dftname = processStringField(csvFields[17]);
this.fid = processStringField(csvFields[18]);
this.roadname = processStringField(csvFields[19]);
}
private static String processStringField(String field) {
// consider empty fields as null
if (field.isEmpty()) {
return null;
}
// strip double quotes and replace any escaped quotes
final int endIndex = field.length() - 1;
if (field.charAt(0) == '"' && field.charAt(endIndex) == '"') {
return field.substring(1, endIndex).replace("\"\"", "\"");
}
return field;
}
public int getRecordNumber() { return recordNumber; }
public String getRoadlink_fid() { return roadlink_fid; }
public String getVersion() { return version; }
public String getVersiondate() { return versiondate; }
public String getChangedate() { return changedate; }
public String getReasonforchange() { return reasonforchange; }
public String getDescriptivegroup() { return descriptivegroup; }
public String getDescriptiveterm() { return descriptiveterm; }
public String getNatureofroad() { return natureofroad; }
public String getLength() { return length; }
public String getDirectednode_href() { return directednode_href; }
public String getDirectednode_orientation() { return directednode_orientation; }
public String getDirectednode_gradeseparation() { return directednode_gradeseparation; }
public String getReferencetotopographicarea_href() { return referencetotopographicarea_href; }
public String getTheme() { return theme; }
public String getFilename() { return filename; }
public String getWkb_geometry() { return wkb_geometry; }
public String getRoadnumber() { return roadnumber; }
public String getDftname() { return dftname; }
public String getFid() { return fid; }
public String getRoadname() { return roadname; }
#Override
public String toString() {
return "roadlink_fid= " + roadlink_fid + "; version= " + version + "; versiondate= "
+ versiondate + "; changedate= " + changedate + "; reasonforchange= "
+ reasonforchange + "; descriptivegroup= " + descriptivegroup + "; descriptiveterm= "
+ descriptiveterm + "; natureofroad= " + natureofroad + "; length= " + length
+ "; directednode_href= " + directednode_href + "; directednode_orientation= "
+ directednode_orientation + "; directednode_gradeseparation= "
+ directednode_gradeseparation + "; referencetotopographicarea_href= "
+ referencetotopographicarea_href + "; theme= " + theme + "; filename= " + filename
+ "; wkb_geometry= " + wkb_geometry + "; roadnumber= " + roadnumber + "; dftname= "
+ dftname + "; fid= " + fid + "; roadname= " + roadname + ";";
}
}
I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
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();
}
I keep getting an error with my program after it craws the first 2 URL's "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0". The first couple of URL's craw as I want them to and I get the text from them using a method in another class. The other class could be the problem I don't know. Please have a look at my code and see whats happening.
package WebCrawler;
import java.util.Scanner;
import java.util.ArrayList;
import static TextAnalyser.Textanalyser.analyse;
public class Crawler {
public static void main(String[] args) {
// java.util.Scanner input = new java.util.Scanner(System.in);
// System.out.print("Enter a URL: ");
// String url = input.nextLine();
crawler("http://www.port.ac.uk/"); // Traverse the Web from the a starting url
}
public static void crawler(String startingURL) {
ArrayList<String> listOfPendingURLs = new ArrayList<String>();
ArrayList<String> listOfTraversedURLs = new ArrayList<String>();
listOfPendingURLs.add(startingURL);
while (!listOfPendingURLs.isEmpty() && listOfTraversedURLs.size() <= 100) {
String urlString = listOfPendingURLs.remove(0);
if (!listOfTraversedURLs.contains(urlString)) {
listOfTraversedURLs.add(urlString);
String text = urlString;
text = ReadTextfromURL.gettext(text);
text = analyse(text);
System.out.println("text : " + text);
System.out.println("Craw " + urlString);
for (String s: getSubURLs(urlString)) {
if (!listOfTraversedURLs.contains(s)) {
listOfPendingURLs.add(s);
}
}
}
}
}
public static ArrayList<String> getSubURLs(String urlString) {
ArrayList <String> list = new ArrayList<String>();
try {
java.net.URL url = new java.net.URL(urlString);
Scanner input = new Scanner(url.openStream());
int current = 0;
while (input.hasNext()) {
String line = input.nextLine();
current = line.indexOf("http:", current);
while (current > 0) {
int endIndex = line.indexOf("\"", current);
if (endIndex > 0) { // Ensure that a correct URL is found
list.add(line.substring(current, endIndex));
current = line.indexOf("http:", endIndex);
} else {
current = -1;
}
}
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return list;
}
}