can't call method in java - java

I have a very stupid problem that's giving me a major headache.
I defined a method which searches an ArrayList to find a zipcode:
public ZipCode findZip (int zip) {
ZipCode aZip = new ZipCode(0);
for(int i = 0; i < zips.size(); i++) {
if(zips.get(i).getZipCode() == zip)
aZip = zips.get(i);
else
aZip = null; }
return aZip; }
...But, I cannot call it for the life of me. It gives me the "cannot find symbol" error every time I call it, no matter what object I use or parameter I input.
The entire program so far (it can't be finished until I figure this out):
import java.util.*;
import java.io.*;
import java.lang.Math;
public class ZipCodeDatabase {
//Field
private ArrayList<ZipCode> zips;
//Constructor
public ZipCodeDatabase () {
zips = new ArrayList<ZipCode> ();
}
//Mutator Method
public void readZipCodeData(String filename) {
Scanner inFS = null;
FileInputStream fileByteStream = null;
try{
// open the File and set delimiters
fileByteStream = new FileInputStream("zipcodes.txt");
inFS = new Scanner(fileByteStream);
inFS.useDelimiter("[,\r\n]+");
// continue while there is more data to read
while(inFS.hasNext()) {
//read in all input
int aZip = inFS.nextInt();
String aCity = inFS.next();
String aState = inFS.next();
double aLat = inFS.nextDouble();
double aLon = inFS.nextDouble();
//Create and add new zipcode
ZipCode newZip = new ZipCode(aZip, aCity, aState, aLat, aLon);
zips.add(newZip);
}
fileByteStream.close();
// Could not find file
}catch(FileNotFoundException error1) {
System.out.println("Failed to read the data file: " + filename);
// error while reading the file
}catch(IOException error2) {
System.out.println("Oops! Error related to: " + filename);
}
}
//Accessor Methods
public ZipCode findZip (int zip) {
ZipCode aZip = new ZipCode(0);
for(int i = 0; i < zips.size(); i++) {
if(zips.get(i).getZipCode() == zip)
aZip = zips.get(i);
else
aZip = null;
}
return aZip;
}
public int distance(int zip1, int zip2) {
int dist = 0;
double p1 = 0.0;
double p2 = 0.0;
double p3 = 0.0;
if(zips.findZip(zip1) == null || zips.findZip(zip2) == null)
dist = -1;
...
The error itself is:
cannot find symbol - Method findZip(int)
You are using a symbol here which has not been declared in any visible scope.
Using ZipCodeDatabase.findZip(int); gives the following compiler error:
non-static method findZip(int) cannot be referenced from a static context
You are trying to reference an instance field or instance method from a static method.
I'm currently working through this, get back with more updates if needed. Thank you for all given help.
ZipCode itself isn't really in play for this issue, its just a bunch of set and get methods for the zips.

The problem comes from this line:
if(zips.findZip(zip1) == null || zips.findZip(zip2) == null)
Going up to the top of your class, we find the declaration of zips, which is
private ArrayList<ZipCode> zips;
This is a problem, because your findZip method is on the ZipCodeDatabase class, not on ArrayList. Since that call is happening from inside of a non-static method of ZipCodeDatabase, you can simply remove the object you're calling it on.
if(findZip(zip1) == null || findZip(zip2) == null)
This is equivalent to using
if(this.findZip(zip1) == null || this.findZip(zip2) == null)
which calls the method on the current instance of the ZipCodeDatabase class.

Try this and see if it works.
ZipCodeDatabase database = new ZipCodeDatabase();
database.readZipCodeData("SomeFilename.txt"); // hardcoded in code as zipcodes.txt
ZipCode myZip = database.findZip(1234);
in the first line you instantiate the class and in the second you load it with data, and in the third you use the same instance to find the code.

Related

How to sort a linked list with objects and private variables

I am going to be honest and up front here. This is homework, but I have become desperate and am looking for anyone to assist me. I have been working on this off and on for over a month and have gone to my instructor multiple times. Basically this program needs to create and sort a linked list that has an int, string and double in each node. It needs to be able to sort by each data type as well as print in input order but once I figure one out I can transfer it to the other data types. Please, everything needs to be "hand made", please do not use any built in commands as I need to create everything as per my instructor's demands.
I attempted to make the linked list and then sort it, but I ran into a problem so I decided to try and sort the list as I create it.
For example: Input the first node, then input the next node in front/behind the first, then put the next where it needs to go... and so forth.
Here is my code (I only focus on the strings):
String repeat = "y";
list1 fChr = null;
list1 p = fChr;
list1 copy = null;
//list1 dCopy = null;
//list1 iCopy = null;
list1 fd = fChr;//front of the double list
list1 fi = fChr;//front of the integer list
list1 fStr = fChr;//front of the string list~
list1 pStr = fStr;
boolean inserted = false;
int iii = 0;
String sss = "";
double ddd = 0.0;
while(repeat.equals("y"))//while the user agrees to adding a new node
{
if(fChr == null)// if the front is empty
{
fChr = new list1();//create a new node by calling object and sets it as the front
p = fChr;
copy = fChr;
sss = fChr.GetS();
iii = fChr.GetI();
ddd = fChr.GetD();
copy.SetS(sss);
copy.SetI(iii);
copy.SetD(ddd);
System.out.println("(1)");
}
else
{
System.out.println("(2)");
if(p!=null)
{
System.out.println("p = "+ p.GetS());
if(p.next != null)
{
System.out.println("p.next = "+ p.next.GetS());
System.out.println("p.next.next = "+ p.next.next.GetS());
}
}
p = fChr;
while(p.next != null)//finds the end of the Linked list
{
System.out.println("(3)");
p = p.next;//moves the pointer p down the list
}
list1 NextNode = new list1();//
p.next = NextNode;
sss = NextNode.GetS();
iii = NextNode.GetI();
ddd = NextNode.GetD();
copy = NextNode;
String gg = "hi";//tests to see if the setter is actually changing the value inside copy(it is not, it prints b)
copy.SetS(gg);
copy.SetI(iii);
copy.SetD(ddd);
System.out.println(copy.GetS());
System.out.println("p = "+ p.GetS());
}
pStr = fStr;
//System.out.println(copy.GetS()+"*");
inserted = false;
if(fStr == null)
{
System.out.println("(4)");
fStr = copy;//fStr = fChr;
inserted = true;
//System.out.println("p.next.next = "+ p.next.next.GetS());
}
else if(copy.GetS().compareTo(fStr.GetS()) < 0)
{
System.out.println("(5)");
//System.out.println("1)p.next.next = "+ p.next.next.GetS());
copy.next = fStr;//ERROR ON THIS LINE
System.out.println("2)p.next.next = "+ p.next.next.GetS());
System.out.println("fChr.next: "+fChr.next.GetS());
fStr = copy;
System.out.println("3)p.next.next = "+ p.next.next.GetS());
inserted = true;
System.out.println("p = "+ p.GetS());
System.out.println("p.next = "+ p.next.GetS());
System.out.println("4)p.next.next = "+ p.next.next.GetS());
}
else if(fStr.next == null && fStr != null)
{
System.out.println("(6)");
fStr.next = copy;
inserted = true;
}
else
{
System.out.println("(7)");
pStr = fStr;
System.out.println("RIP (8)");
while(pStr.next != null && inserted == false)
{
System.out.println("(9)");
System.out.println("RIP");
if(copy.GetS().compareTo(pStr.next.GetS()) < 0)//if it goes between 2 nodes
{
System.out.println("(10)");
copy.next = pStr.next;
pStr.next = copy;
inserted = true;
}
else
{
System.out.println("(11)");
pStr = pStr.next;
}
if(pStr.next == null && inserted == false)// it goes at the end(not necessary bc of the (in order) part)
{
System.out.println("(12)");
pStr.next = copy;
}
}
}
repeat = JOptionPane.showInputDialog("Would you like to add a node [y/n]");
System.out.println("End of Loop");
}
System.out.println(fStr.GetS());
PrintMenu(fChr, fi, fd, fStr);// sends the user to the menu screen
}
From all of my print statements I have (what I think) found the problem. This code runs through twice and upon hitting "y" for the third time, prints "(3)" in an infinite loop. I have found that (say the input for the strings is "c" then "b") "p" is equal to "c", p.next is equal to "b" and p.next.next is equal to "c". So, p is in an infinite loop. I have no idea why it does this, I have a theory that it could be because the front(fChr) changes and then "p" points to it and is just kinda drug along. I also just realized that me trying to set "copy" equal to "NextNode" was unsuccessful and copy just holds the value inside p.next(which is NextNode). That seems correct, but when I try to put something else in, it doesn't work. I could be testing this incorrectly and in that case the setter is correct. Setting is one of the main problems that I seem to be having. I will try to answer as many questions as I can if anyone has any.
Also here is the object in case you would like to see it. Thank you for your time, any help will be appreciated. Please if possible try to keep it relatively simple this is a high school assignment and I am so close and am stumped on how to fix what is wrong. Also, you may have noticed, but I have to use private variables. I am not asking for someone to give me a program that works, I am just asking if you know why what is going wrong is happening and if you know how to fix it. Thank you from the bottom of my heart!
import javax.swing.JOptionPane;
public class list1
{
private int i;
private String s;
private double d;
private String ss = null;
private int ii = 0;
private double dd = 0.0;
list1 next = null;
public list1()
{
String str;
s=JOptionPane.showInputDialog("Enter a String");
String temp =JOptionPane.showInputDialog("Enter an Integer");
i = Integer.parseInt(temp);
String temp2 =JOptionPane.showInputDialog("Enter a Double");
d = Double.parseDouble(temp2);
}
public double GetD()
{
return d;
}
public String GetS()
{
return s;
}
public int GetI()
{
return i;
}
public void SetS(String x)
{
ss = x;
}
public void SetI(int y)
{
ii = y;
}
public void SetD(double z)
{
dd = z;
}
}

How to extend a class array/ call class array attributes after extend a class?

for a larg-DB based dynamically-multiple-area-menu, I created a class MenuPoint:
class MenuPoint{
public int areaId;
public int preID;
public String name;
public String desc;
public String stepInImg = "bsp.img";
public String stepOutImg = "bsp.img";
public String detailedForm = "bsp.fxml";
public String detailedImg = "bsp.img";
public String [] additionalOptionForm = new String[0];
public String [] additionalOptionName = new String[0];
public String [] additionalOptionImg = new String[0];}
and initialised it as an 0-length array in my main class: MenuController
public MenuPoint [] menuItem = new MenuPoint[0];
I use a API call to get my DB stored information by initialisation of MenuController.
I store the results by using the following code:
int dataStructlength = 12;
String[] exampleApiResultKeys = new String[dataStructlength];
exampleApiResultKeys[0] = "SITE_NUMBER";
exampleApiResultKeys[1] = "SITE_DESC";
exampleApiResultKeys[2] = "SITE_NUMBER_EXT";
exampleApiResultKeys[3] = "CELL_NUMBER";
exampleApiResultKeys[4] = "CELL_DESC";
exampleApiResultKeys[5] = "CELL_TYPE";
exampleApiResultKeys[6] = "MACHINE_GROUP_NUMBER";
exampleApiResultKeys[7] = "MACHINE_GROUP_DESC";
exampleApiResultKeys[8] = "MACHINE_GROUP_TYPE";
exampleApiResultKeys[9] = "STATION_NUMBER";
exampleApiResultKeys[10] = "STATION_DESC";
exampleApiResultKeys[11] = "STATION_TYPE";
exampleApiController.test_mdataGetMachineAssetStructure(exampleApiFilter, exampleApiResultKeys);
for(int i = 0; exampleApiController.resultValues.value != null && i < exampleApiController.resultValues.value.length/12; i++)
{
boolean isUseless = false;
for(int a = 0; a < dataStructlength; a ++)
if(true == exampleApiController.resultValues.value[i*dataStructlength+a].trim().isEmpty())
isUseless = true;
if(!isUseless)
{
int preId= -1;
if("M".equals(exampleApiController.resultValues.value[i*12+5]))
{
if(giveItemId(0, preId, exampleApiController.resultValues.value[i*12]) >= 0)
preId = giveItemId(0, preId, exampleApiController.resultValues.value[i*12]);
else
preId = addMenuItem(0, preId, exampleApiController.resultValues.value[i*12], exampleApiController.resultValues.value[i*12+1], "bsp.form");
}
if("M".equals(exampleApiController.resultValues.value[i*12+5]))
{
if(giveItemId(1, preId, exampleApiController.resultValues.value[i*12+3]) >= 0)
preId = giveItemId(0, preId, exampleApiController.resultValues.value[i*12+3]);
else
preId = addMenuItem(1, preId, exampleApiController.resultValues.value[i*12+3], exampleApiController.resultValues.value[i*12+4], "bsp.form");
}
if("M".equals(exampleApiController.resultValues.value[i*12+8]))
{
if(giveItemId(2, preId, exampleApiController.resultValues.value[i*12+6]) >= 0)
preId = giveItemId(0, preId, exampleApiController.resultValues.value[i*12+6]);
else
preId = addMenuItem(2, preId, exampleApiController.resultValues.value[i*12+6], exampleApiController.resultValues.value[i*12+7], "bsp.form");
}
if("M".equals(exampleApiController.resultValues.value[i*12+11]))
{
if(giveItemId(3, preId, exampleApiController.resultValues.value[i*12+9]) >= 0)
preId = giveItemId(0, preId, exampleApiController.resultValues.value[i*12+9]);
else
preId = addMenuItem(3, preId, exampleApiController.resultValues.value[i*12+9], exampleApiController.resultValues.value[i*12+10], "bsp.form");
}
}
giveItemId:
public int giveItemId(int areaId_temp, int preId_temp, String name_temp)
{
for(int i = 0; i < menuItem.length; i++)
{
if(menuItem[i].areaId == areaId_temp && menuItem[i].name.equals(name_temp) && menuItem[i].preID == preId_temp)
return i;
}
return -1;
}
addMenuItem:
public int addMenuItem(int areaId_temp, int preId_temp, String name_temp, String desc_temp, String form_temp)
{
Object newArray1 = Array.newInstance(menuItem.getClass().getComponentType(), Array.getLength(menuItem)+1); // +1 Arrayfeld
System.arraycopy(menuItem, 0, newArray1, 0, Array.getLength(menuItem));
menuItem = (MenuPoint[]) newArray1; // expend but missing attributes
menuItem[menuItem.length-1].areaId = areaId_temp;
menuItem[menuItem.length-1].preID = preId_temp;
menuItem[menuItem.length-1].name = name_temp;
menuItem[menuItem.length-1].desc = desc_temp;
menuItem[menuItem.length-1].detailedForm = form_temp;
return menuItem.length-1;
}
I found out that menuItem donsĀ“t carry any attributes after expending it.
Do I have to create "new" Instances of MenuPoint to make it work?
Is it even possible to expend a class-array without loosing attributes or their values?
It shoud, because in the end menuItem is just a pointer-array, pointing on multiple workstorage-addresses, aren't it?
Thank you guys for any tips or better concept you can give me. (I know this class-concept is silly but I have no idea for a better one)
And please excuse my bad grammar.
You create a new array in method addMenuItem which is then populated with the members from the existing menuItem, but the element at index (new) length - 1 isn't initialized:
menuItem[menuItem.length-1] = new MenuPoint();
You should have gotten a NullPointerException when trying to set the fields.
All this usage of java.lang.reflect.Array is rather contrived. There are simpler ways to achieve this. Here is a simplified versio of addMenuItem
public int addMenuItem(int areaId, String name){
MenuPoint[] newMenuItem = new MenuPoint[menuItem.length + 1];
System.arraycopy(menuItem, 0, newMenuITem, 0, menuItem.length);
menuItem = newMenuItem;
menuItem[menuItem.length-1] = new MenuPoint();
menuItem[menuItem.length-1].areaId = areaId;
menuItem[menuItem.length-1].name = name;
return menuItem.length; // Why -1 ?
}
But, above all, do use a List<MenuPoint>.
For the answer of your question Do I have to create "new" Instances of MenuPoint to make it work?
Yes
From your code snippets you need to initialize MenuPoint class object to store its values to the array menuItem.
Initialize your array element with below line
menuItem[menuItem.length-1] = new MenuPoint();
Place above line after copying your array by menuItem = (MenuPoint[]) newArray1;
Without initialization there is NullPointerException exception for setting values to null object.
There are some better ways to maintain list of object using ArrayList class.
To use ArrayList you need following code change
public List<MenuPoint> menuItem = new ArrayList<MenuPoint>; //Initialize list
Your Function will be
public int addMenuItem(int areaId_temp, int preId_temp, String name_temp, String desc_temp, String form_temp)
{
MenuPoint menuPoint = new MenuPoint();
menuPoint.areaId = areaId_temp;
menuPoint.preID = preId_temp;
menuPoint.name = name_temp;
menuPoint.desc = desc_temp;
menuPoint.detailedForm = form_temp;
menuItem.add(menuPoint);
return menuItem.size()-1;
}
I think this is easy than using reflection with array.

calling a method(constructor) from main & file format

I have a constructor ID3 and I need to start by executing it from the main. Is it possible?
I tried doing this:
public class ID3
{
public static void main(String[] args) throws Exception
{
System.out.print("\f"); //clears the screen
ID3 instance = new ID3("data.txt", 5 , 14 , "", 5);
instance.ID3("data.txt", 3 , 5 , " ", 2); //error given here since this line had to be removed
}
public ID3(String fName, int numAttributes, int testCases, String delimiter, int limitSplits) throws IOException, FileNotFoundException
{
fileName = fName;
n = numAttributes;
t = testCases;
numSplits = limitSplits;
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
//Parse the first line to see if continuous or discrete attributes.
firstLine = new String[n];
firstLine = in.readLine().split(delimiter);
int i, j, lineCount = 0;
for(i=0; i<n; i++)
unusedAttr.add(new Integer(i));
input = new String[t][n+1];
String line;
int invalidLines = 0;
while((lineCount + invalidLines)<t)
{
try
{
input[lineCount] = (in.readLine()).split(delimiter);
}
catch(NullPointerException e)
{
invalidLines++;continue;
}
if (Array.getLength(input[lineCount]) != n+1 || (Array.get(input[lineCount],n).toString().compareTo("?") == 0)) //number of attributes provided in the line is incorrect.
{
invalidLines++;continue;
}
lineCount++;
}
if(invalidLines == t)
{
System.out.println("All lines invalid - Check the supplied attribute number");
System.exit(0);
}
if (invalidLines > 0)
System.out.println("Not Considering "+invalidLines+" invalid training cases");
if(numSplits > maxSplits || numSplits > (t/2))
{
System.out.println("numSplits should be less than or equal to "+Math.min(t/2,limitSplits));
System.exit(1);
}
t = testCases - invalidLines;
thresholdVal = new String[n][numSplits - 1];
boolean allCont = false;
if(Array.getLength(firstLine) == 1)
{
if(firstLine[0].compareTo("c") == 0)
allCont = true;
else if(firstLine[0].compareTo("d") == 0)
return;
else
{
System.out.println("Invalid first line - it should be c or d");
System.exit(1);
}
}
for(i=0; i<n; i++)
{
if(allCont || firstLine[i].compareTo("c") == 0) //Continuous Attribute
{
for(j=0; j<numSplits-1; j++)
thresholdVal[i][j] = calculateThreshold(i,j);
}
else if(firstLine[i].compareTo("d") != 0)
{
System.out.println("Invalid first line - Training data (it should specify if the attributes are c or d)");
System.exit(1);
}
}
for(i=0; i<t; i++)
{
for(j=0; j<n; j++)
{
if(allCont || firstLine[j].compareTo("c") == 0)
input[i][j] = makeContinuous(input[i][j], j);
}
}
}
The code for the constructor is shown above, however it finds the file but doesn't process the data and prints the errors out. How should the file be exactly?
Used text file has:
d
Span Shape Slab
long square waffle
long rectangle waffle
short square two-way
short rectangle one-way
You are already calling the constructor here - ID3 instance = new ID3("data.txt", 5 , 14 , "", 5);. You can't call it as a regular method. Just remove the instance.ID3("data.txt", 5 , 14 , "", 5); line.
You cannot call constructors like regular methods. The constructor is automatically called when you create an instance of a class,i.e,when you do
ID3 instance = new ID3("data.txt", 5 , 14 , "", 5);
Contructors are not methods. One of the key feature of a method is that it should have a return type (event if it is 'void').
Here, you do not need to explicitly call the constructor again. The functionality you implement in the constructor will be executed at instantiation itself. However, this is not recommended and is bug-prone. You should only be instantiating any variables. The actual functionality should be defined in another method.

Java - object existence dilem

I wrote the following, this is a toString of a Country class that has City class in same package, and _cities is an array represents the cities within my Country:
**EDITED:**
public String toString(){
String allCitiesData = ""; //must be initialized
for(int i=0;this._cities[i] != null;i++)//run all over the cities until reach the end(null cell)
{ //concat new city to the string and adds a new line between
allCitiesData = allCitiesData.concat(this._cities[i].toString()+"\n\n");
}
return allCitiesData;
}//toString method
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
Point referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}//citiesNorthOf method
But, when I run it, it shows a single error only on this line:
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
And the Eclipse says: "referenceCityCenter cannot be resolved to a variable".. any suggestions ?
Thanks !!
You have declared referenceCityCenter in a scope which is not visible to that line of your code. Try declaring it at the beginning of the method (and control too if it is null when it arrives to your validation .isAbove()! :P )
referenceCityCenter is out of scope. Put it outside of your if statement and make sure you check for null afterwards like follows:
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
Point referenceCityCenter = null;
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (referenceCityCenter !- null && this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}

Child Class Attribute error

I have a child (extended) class with a protected attribute height.
I want to access it in the main program:
while(line != null)
{
String[] field = line.split("#");
int height = Integer.parseInt(field[0]);
if (field.length ==1)
{
forest[cnt] = new Trees(height);
}
else
{
forest[cnt] = new Shrub(height, field[1]);
}
cnt++;
line = inS.readLine();
}
inS.close();
String s = JOptionPane.showInputDialog("Enter Name to search for");
for(int i = 0; i<forest.length; i++)
{
if (forest[i] instanceof Shrub)
{
String a = forest[i].getName();
System.out.println ("Found");
}
}
}
However I get an error saying that it cannot find the method getName, however when i run the lol Shrub it works fine?
Thanks.
Private access modifier methods are not accessible in child class. Make them Public or Protected.

Categories