I have a list of values (Weather data), the people who wrote the list used the value "9999" when they did not have a value to report. I imported the text file and used the following code to take the data, and edit it:
import java.io.*;
import java.util.*;
public class weatherData {
public static void main(String[] args)
throws FileNotFoundException{
Scanner input = new Scanner(new File("PortlandWeather2011.txt"));
processData(input);
}
public static void processData (Scanner stats){
String head = stats.nextLine();
String head2 = stats.nextLine();
System.out.println(head);
System.out.println(head2);
while(stats.hasNextLine()){
String dataLine = stats.nextLine();
Scanner dataScan = new Scanner(dataLine);
String station = null;
String date = null;
double prcp = 0;
double snow = 0;
double snwd = 0;
double tmax = 0;
double tmin = 0;
while(dataScan.hasNext()){
station = dataScan.next();
date = dataScan.next();
prcp = dataScan.nextInt();
snow = dataScan.nextInt();
snwd = dataScan.nextInt();
tmax = dataScan.nextInt();
tmin = dataScan.nextInt();
System.out.printf("%17s %10s %8.1f %8.1f %8.1f %8.1f %8.1f \n", station, date(date), prcp(prcp), inch(snow), inch(snwd), temp(tmax), temp(tmin));
}
}
}
public static String date(String theDate){
String dateData = theDate;
String a = dateData.substring(4,6);
String b = dateData.substring(6,8);
String c = dateData.substring(0,4);
String finalDate = a + "/" + b + "/" + c;
return finalDate;
}
public static double prcp(double thePrcp){
double a = (thePrcp * 0.1) / 25.4;
return a;
}
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = 9999;
}
return a;
}
public static double temp(double theTemp){
double a = ((0.10 * theTemp) * 9/5 + 32);
return a;
}
}
The problem I am having is taking the values and checking for all times "9999" comes up, and printing out "----". I don't know how to take in a value of type double, and print out a String.
This code takes the values and checks for the value 9999, and does nothing with it. This is where my problem is:
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = "----";
}
return a;
}
I'm sorry if I put to much information into this question. If you need me to clarify just ask. Thanks for any help!
You need to modify your inch function to return a string, not a double.
public static String inch(double theInch){
if(theInch == 9999){
return "----";
}
return Double.toString(theInch/25.4);
}
I think the first problem might be that you're reading all the values from the Scanner as int instead of doubles. For example, based on your System.out.println() statement, I think you should actually be reading the following data types...
prcp = dataScan.nextDouble();
snow = dataScan.nextDouble();
snwd = dataScan.nextDouble();
tmax = dataScan.nextDouble();
tmin = dataScan.nextDouble();
Also, seeing as though the inch() method is only going to be used in the System.out.println() line, you'll need to change it to a String as the return type...
public String inch(double theInch){
if (theInch == 9999){
return "----";
}
return ""+(theInch/25.4);
}
Related
I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.
public enum Operator {
PLUS("+"),
MINUS("-");
private final String operator;
Operator(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator getByValue(String operator) {
for (Operator operatorEnum : Operator.values()) {
if (operatorEnum.getOperator().equals(operator)) {
return operatorEnum;
}
}
throw new IllegalArgumentException("Invalid value");
}
}
//////////
public enum MetricConvertor {
m(1000),
cm(10),
mm(1),
km(1000000),
dm(100);
private int scale;
MetricConvertor(int scale) {
this.scale = scale;
}
public int getScale() {
return scale;
}
}
/////////
public class Application {
public static void main(String[] args) {
int scale = MetricConvertor.valueOf("m").getScale();
}
I wan to create a calculator that is capable of computing a metric distance value from an expression that contains different scales and systems.
Output should be specified by the user.
Only Addition and subtraction is allowed.
Output is in lowest unit.
Expression: 10 cm + 1 m - 10 mm
Result: 1090 mm
I am stuck at this point, how can I add or substract the values for a list and convert them at the lowest scale sistem( eg above mm, but it can be dm if are added for example dm + m + km)
Here is solution
split each string by add/minus and add it to appropriate list
split number and metric in each list(can use matcher) and sum it
result = sumAdd - sumMinus(mm).
Please optimize it, because i don't have time to optimize this code, I need to go to bed :D
Result is in mm, so you have to get lowest metric and recaculate it(leave it to you).
private static int caculator(String exp) {
List<String> addList = new ArrayList<>();
List<String> minusList = new ArrayList<>();
int checkPoint = 0;
boolean op = true;//default first value is plus
// Split string with add/minus
for (int i = 1; i < exp.length(); i++) {
String s = exp.substring(i, i + 1);
if (Operator.PLUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = true;
continue;
}
if (Operator.MINUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = false;
continue;
}
}
// Add last string
checkOperator(addList, minusList, op, exp.substring(checkPoint).trim());
// Get sum each list
int sumAdd = sumList(addList);
int sumMinus = sumList(minusList);
return sumAdd - sumMinus;
}
//sum a list
private static int sumList(List<String> addList) {
int sum = 0;
for (String s: addList) {
String[] arr = s.split(" ");
int value = Integer.parseInt(arr[0]);
int scale = MetricConvertor.valueOf(arr[1]).getScale();
sum += value * scale;
}
return sum;
}
// check operator to put into approriate list
private static void checkOperator(List<String> addList, List<String> minusList, boolean op, String substring) {
if (op) {
addList.add(substring);
} else {
minusList.add(substring);
}
}
The goal of the application is as following: I want to create objects (airplanes) of the class "Flugzeug" (German word for airplane). I want to create an array which refers to the different attributes of the objects.
The problem is (as far as I know) that one single array can only refer to variables of the exact same type.
How can I change my program that it works? Is it inevitable to create an array for each attribute (e.g. for each different type of variable)?
The code:
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug [] airline = new Flugzeug [4];
for (int i = 0; i < 4; i=i+1){
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[0].idNumber = "1";
airline[0].seats = "165";
airline[0].velocity = "890";
airline[0].range = "12600";
airline[1].type = "Boeing 747";
airline[1].idNumber = "2";
airline[1].seats = "416";
airline[1].velocity = "907";
airline[1].range = "12700";
airline[2].type = "Avro RJ 85";
airline[2].idNumber = "3";
airline[2].seats = "93";
airline[2].velocity = "760";
airline[2].range = "2200";
airline[3].type = "Airbus 380";
airline[3].idNumber = "4";
airline[3].seats = "516";
airline[3].velocity = "907";
airline[3].range = "12000";
}
for (int i=0; i < 4; i=i+1) {
airline[i].printInfo();
double time = airline[i].getTime(6320); //distance from Zurich to New York
System.out.println("duration: " + time + " h");
int capacity = airline[i].getCapacity(365);
System.out.println("capacity: " + capacity + " passengers / year");
}
}
}
public class Flugzeug {
String type;
int idNumber;
int seats;
double velocity;
double range;
double distance;
int days;
public void printInfo() {
System.out.println("type: " + this.type);
System.out.println("ID-number: " +this.idNumber);
System.out.println("seats: " + this.seats);
System.out.println("velocity: " + this.velocity);
System.out.println("range: " + this.range);
}
public double getTime (double dist) {
double result = 0;
result = dist / velocity;
double time = result;
return time;
}
public int getCapacity(int days) {
int capacity = seats * days;
return capacity;
}
}
The core of your problem is this:
one single array can only refer to variables of the exact same type.
That is correct (or mostly correct, all elements of an array must have a common base type, but that's not a relevant distinction right now).
But the type inside of your array is Flugzeug, not String!
So each element of the array must be a Flugzeug. That doesn't mean that the fields of that class have to all share a single type (and indeed, as you posted, they don't).
Look at this line:
airline[0].idNumber = "1";
this is almost correct, but since idNumber is an int you must assign it an int value (such as 1) instead:
airline[0].idNumber = 1;
The second (mostly unrelated) problem is that you try to access all 4 Flugzeug instances inside of the loop that creates them. That means when you try to access the second instance after just having created the first one (only!) it will crash:
Replace this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
}
with this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
}
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
if some type like int,double,long... was used " " ,They almost all become String type
I found two problems with your code.
First, you have declared idNumber as int int idNumber; but while assigning the value you are inserting a string value airline[0].idNumber = "1";.
NOTE: "1" is a string not integer.
The solution here would be airline[0].idNumber = 1;
You need to assign same type of values to every variable as they are declared.
And second, you are creating multiple objects in the loop airline[i] = new Flugzeug (); but overwriting the same single object (stored in the 0th position of the array) everytime. I would suggest to do,
airline[i].type = "A320";
airline[i].idNumber = 1; // Again this should not be "1"
airline[i].seats = 165; // And this should not be "165"
airline[i].velocity = 890; // Same is applicable here
airline[i].range = 12600; // and here
The problem is the variables are not only String type but ints and doubles as well. You need to assign the correct type. In addition you shouldn't access class variables like that, make them private create a constructor with getters and setters.
public class Flugzeug {
private String type;
private int idNumber;
private int seats;
private double velocity;
private double range;
private double distance;
private int days;
public Flugzeug(String type, int idNumber, int seats, double velocity, double range) {
this.type = type;
this.idNumber = idNumber;
this.seats = seats;
this.velocity = velocity;
this.range = range;
}
public double getDistance() {
return this.distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug[] airline = new Flugzeug [4];
airline[0] = new Flugzeug("A320", 1, 165, 890, 12600);
airline[1] = new Flugzeug(...);
}
}
As the title says, I cannot convert my ArrayList into an Array. The data type of my ArrayList is a custom object but I cannot seem to find what my problem is. The error that it gives doesn't show up as a problem until the program is run. The first two classes are the objects, then I have a class calle Tester where the main method is.
Class where error appears:
package backend;
import java.util.ArrayList;
public class Function {
Coefficient[] coefArray;
int constant;
public Function(ArrayList<Coefficient> coefFunction, int constant){
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
this.coefArray = sortArray(coefArray);
this.constant = constant;
}
private Coefficient[] sortArray(Coefficient[] newArray){
int tempPow = -1000000000;
Coefficient[] sortedArray = new Coefficient[newArray.length];
sortedArray = null;
for(int i=0; isFull(sortedArray); i++){
for(Coefficient coef : newArray){
if(coef.pow>tempPow){
tempPow = coef.pow;
sortedArray[i] = coef;
}
}
}
return sortedArray;
}
private boolean isFull(Coefficient[] anArray){
for(Coefficient i : anArray) {
if(i == null) return true;
}
return false;
}
public String toString(){
String compiledString="";
for(Coefficient coef : coefArray){
compiledString += coef.toString()+"+";
}
if(constant==0){
//No constant there
}else{
compiledString = compiledString + constant;
}
return compiledString;
}
}
Coefficient Class:
package backend;
public class Coefficient {
String stringVersion;
public int pow;
public int coefInteger;
public double coefDouble;
//Constructor for variable with a coefficient that is non-fractal and a power higher than 1
public Coefficient(int coef, int pow){
this.coefInteger = coef;
this.pow = pow;
switch(coef){
case 0:
//Do nothing here
case 1:
this.stringVersion = "x^"+pow;
break;
default:
this.stringVersion = coef+"x^"+pow;
break;
}
}
//Constructor for variable with a coefficient that is fractal and a power higher than 1
public Coefficient(double coef, int pow){
this.coefDouble = coef;
this.pow = pow;
this.stringVersion = coef+"x^"+pow;
}
//Constructor for variable with a coefficient but no power
public Coefficient(double coef){
this.coefDouble = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
//Constructor for variable with a coefficient but no power
public Coefficient(int coef){
this.coefInteger = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
public String toString(){
return stringVersion;
}
}
Tester:
package backend;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Coefficient> function = new ArrayList<Coefficient>();
Coefficient xVal;
Function printFunction;
System.out.println("Enter the degree of the equation:");
int pow = scan.nextInt();
System.out.println("Enter the x components of the function in the order of coefficient then power. Enter constant last:");
double coef = 0;
while(pow>0){
coef = scan.nextDouble();
if(pow==1){
if((int) coef == coef){
xVal = new Coefficient((int) coef);
}else{
xVal = new Coefficient(coef);
}
}else{
if((int) coef == coef){
xVal = new Coefficient((int) coef, pow);
}else{
xVal = new Coefficient(coef, pow);
}
}
function.add(xVal);
pow--;
}
System.out.println("Enter the constant:");
printFunction = new Function(function, scan.nextInt());
System.out.println(printFunction.toString());
}
}
Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
cannot be cast to [Lbackend.Coefficient;
at backend.Function.<init>(Function.java:11)
at backend.Tester.main(Tester.java:36)
Any and all help is greatly appreciated. If you see something else that needs to be fixed, please point it out.
The error is in this line:
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
If you read the javadoc of toArray(), you can see that it returns an Object[], which you cannot simply cast to Coefficient[].
Instead use toArray(T[] a):
Coefficient[] coefArray = coefFunction.toArray(new Coefficient[coefFunction.size()]);
Disclaimer: I did not review the rest of your code, so the absence of any remarks does not imply that everything else is fine.
I posted this question earlier but not with the code in its entirety. The coe below also calls to other classes Background and Hydro which I have included at the bottom.
I have a Nullpointerexception at the line indicate by asterisks. Which would suggest to me that the Collections are not storing data properly. Although when I check their size they seem correct.
Thanks in advance. PS: If anyone would like to give me advice on how best to format my code to make it readable, it would be appreciated.
Elliott
>package exam0607;
>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collection;
import java.util.Scanner;
import java.util.Vector;
>import exam0607.Hydro;
import exam0607.Background;// this may not be necessary???? FIND OUT
>public class HydroAnalysis {
public static void main(String[] args) {
Collection<Hydro> hydroList = null;
Collection<Background> backList = null;
try{hydroList = readHydro("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_data.dat");}
catch (IOException e){
e.getMessage();}
try{backList = readBackground("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_bgd.dat");
//System.out.println(backList.size());
}
catch (IOException e){
e.getMessage();}
for(int i =0; i <=14; i++ ){
String nameroot = "HJK";
String middle = Integer.toString(i);
String hydroName = nameroot + middle + "X";
System.out.println(hydroName);
ALGO_1(hydroName, backList, hydroList);
}
}
public static Collection<Hydro> readHydro(String url) throws IOException {
URL u = new URL(url);
InputStream is = u.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader b = new BufferedReader(isr);
String line ="";
Collection<Hydro> data = new Vector<Hydro>();
while((line = b.readLine())!= null){
Scanner s = new Scanner(line);
String name = s.next();
System.out.println(name);
double starttime = Double.parseDouble(s.next());
System.out.println(+starttime);
double increment = Double.parseDouble(s.next());
System.out.println(+increment);
double p = 0;
double nterms = 0;
while(s.hasNextDouble()){
p = Double.parseDouble(s.next());
System.out.println(+p);
nterms++;
System.out.println(+nterms);
}
Hydro SAMP = new Hydro(name, starttime, increment, p);
data.add(SAMP);
}
return data;
}
public static Collection<Background> readBackground(String url) throws IOException {
URL u = new URL(url);
InputStream is = u.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader b = new BufferedReader(isr);
String line ="";
Vector<Background> data = new Vector<Background>();
while((line = b.readLine())!= null){
Scanner s = new Scanner(line);
String name = s.next();
//System.out.println(name);
double starttime = Double.parseDouble(s.next());
//System.out.println(starttime);
double increment = Double.parseDouble(s.next());
//System.out.println(increment);
double sum = 0;
double p = 0;
double nterms = 0;
while((s.hasNextDouble())){
p = Double.parseDouble(s.next());
//System.out.println(p);
nterms++;
sum += p;
}
double pbmean = sum/nterms;
Background SAMP = new Background(name, starttime, increment, pbmean);
//System.out.println(SAMP);
data.add(SAMP);
}
return data;
}
public static void ALGO_1(String hydroName, Collection<Background> backgs, Collection<Hydro> hydros){
//double aMin = Double.POSITIVE_INFINITY;
//double sum = 0;
double intensity = 0;
double numberPN_SIG = 0;
double POSITIVE_PN_SIG =0;
//int numberOfRays = 0;
for(Hydro hd: hydros){
System.out.println(hd.H_NAME);
for(Background back : backgs){
System.out.println(back.H_NAME);
if(back.H_NAME.equals(hydroName)){//ERROR HERE
double PN_SIG = Math.max(0.0, hd.PN - back.PBMEAN);
numberPN_SIG ++;
if(PN_SIG > 0){
intensity += PN_SIG;
POSITIVE_PN_SIG ++;
}
}
}
double positive_fraction = POSITIVE_PN_SIG/numberPN_SIG;
if(positive_fraction < 0.5){
System.out.println( hydroName + "is faulty" );
}
else{System.out.println(hydroName + "is not faulty");}
System.out.println(hydroName + "has instensity" + intensity);
}
}
}
THE BACKGROUND CLASS
package exam0607;
public class Background {
String H_NAME;
double T_START;
double DT;
double PBMEAN;
public Background(String name, double starttime, double increment, double pbmean) {
name = H_NAME;
starttime = T_START;
increment = DT;
pbmean = PBMEAN;
}}
AND THE HYDRO CLASS
public class Hydro {
String H_NAME;
double T_START;
double DT;
double PN;
public double n;
public Hydro(String name, double starttime, double increment, double p) {
name = H_NAME;
starttime = T_START;
increment = DT;
p = PN;
}
}
Ah. Your Hydro class is completely wrong. You're assigning the parameters to the uninitialised members.
e.g.
public Hydro(String name, double starttime, double increment, double p) {
name = H_NAME;
but H_NAME is uninitialised. You need to reverse these e.g.
public Hydro(String name, double starttime, double increment, double p) {
H_NAME = name;
Some hints:
write a toString() method for each class, so you can print it out meaningfully
declare your method parameters as final if you don't expect them to change
declare your member variables to be final if you expect your class to be immutable (unchanging)
investigate unit tests and JUnit
In the above, 1. makes debugging easier 2. and 3. means that the compiler will prevent you from the (all too common) mistake above (try preceeding your method parameters with final and see what happens!) 4. will force you to test at a low level and keep your code correct.
For debugging purposes it's useful to only deference one reference at a time. This helps you identify unexpected null references e.g. if the following gives a NullPointerException
a.getB().getC().getD()
which of a, getB(), getC() gave the null reference ? Dereferencing one per line is more verbose but will give you much more info (object purists will object to the above and refer you to the Law Of Demeter - I shall ignore that for this example).