June 25, 2013

Java: silly newbie issue about path used in import statement

Ggkmath’s Question:

I’m working through the example here:

http://www.vogella.com/articles/JavaPDF/article.html

In my file, I’ve got:

package com.mycompanyname.mydirectory;

import com.mycompanyname.OneOfMyClasses;
import com.itextpdf.text.Document;
...

 public class MyClass {
     ...
 }

Everything is working fine. What I don’t understand is that since I just copied the import statement directly from the link above for the iText portion — why does com.itextpdf.text.Document work?

I mean, if I look in directory com.mycompanyname I can see OneOfMyClasses.java there.

But in the com directly, there is no itextpdf directory (although maybe my user doesn’t have permission to see it(?)).

Hoping someone can help me understand what I’m missing here. Doesn’t the import point to a specific directory that I should be able to see the class? Is there a different com directory somewhere that iText is using, and com.itextpdf.text points to there? (if so, where’s the directory located)?

I installed the jar file for iText in the lib folder as per usual, and made sure it was included in the classpath.

Those classes are inside a JAR file that is added to the classpath:

Create a new Java project “de.vogella.itext.write” with the package “de.vogella.itext.write”. Create a folder “lib” and put the iText library (jar file) into this folder. Add the jar to your classpath.

import statements will look inside whatever directory trees are in the classpath, which includes the current directory at compilation time (tipically the src/ directory in your project) as well as any directory specified through environment variable or JVM startup parameter. See this about the classpath.

EDIT

You do need the imports whenever you use classes across packages. Every public class/interface you define is in a package. If whatever you are referencing belongs to another package, you need to import it.

JARs are zip files that contain directories and files inside. It’s the same as plain directories and files, only packed.

That class is most probably imported in a JAR library. Inside such JAR file, the class files are kept in exact package/folder structure as you use when importing them.

June 24, 2013

Converting a stand alone java file to a file that's part of a project package?

Sam Peterson’s Question:

I still don’t fully understand where I’m required to use the “public static void main(String[] args)” header within the .java files of a project. Do you need to put that header in every .java file of a package?

I have been following along with chapter 3 in my book, dragging and dropping downloaded stand alone book source files into my project’s package, but some of the .java files in my package don’t like that “public static void main(String[] args)” statement, even though my opening and closing curly braces are in the correct place. Here’s an example of one of those files (the ERROR(S) are described in the code’s comments):

    public class Rectangle
{
   public static void main(String[] args){
   private double length;//ERROR: illegal start of expression
   private double width;

   /**
    * Constructor
    */

   public Rectangle(double len, double w)
   {
      length = len;
      width = w;
   }

   /**
    * The setLength method accepts an argument
    * that is stored in the length field. 
    */

   public void setLength(double len)
   {
      length = len;
   }

   /**
    * The setWidth method accepts an argument
    * that is stored in the width field.
    */

   public void setWidth(double w)
   {
      width = w;
   }

   /**
    * The set method accepts two arguments
    * that are stored in the length and width
    * fields.
    */

   public void set(double len, double w)
   {
      length = len;
      width = w;
   }

   /**
    * The getLength method returns the value
    * stored in the length field.
    */

   public double getLength()
   {
      return length;
   }

   /**
    * The getWidth method returns the value
    * stored in the width field.
    */

   public double getWidth()
   {
      return width;
   }

   /**
    * The getArea method returns the value of the
    * length field times the width field.
    */

   public double getArea()
   {
      return length * width;
   }

}//end of: public static void main(String[] args)

}//end of: public class Rectangle  ERROR: class, interface, or enum expected

The ERROR(S) came up after I added the “public static void main(String[] args)” to the existing Rectangle.java file. Any idea of why this occurs?

This occurs because You cannot have more than one main() method in a package. However overriding the main method is definitely allowed. What I mean is as, long the parameter number is differed you can override main() method.

public static void main(String[] args) {
   .....
}

And somewhere else in other or same class, you can add such class

public static void main(String arg1, String arg2) {
    .....
}

The ERROR: illegal start of expression is because you are using access modifier inside the method. Use all the access mofifier and variable declaration inside the class

public class Rectangle {

    private double length;//ERROR: illegal start of expression   
    private double width;

    public static void main(String[] args) {
    ....
    }
}

The ERROR: class, interface, or enum expected is because the class Rectangle is only housing a static method, your all the methods and parameters are inside the static method called main()

Here is your code which will compile without an error.

June 20, 2013

Access an internally used list

Pulz’s Question:

I’m coding the Dijkstra algorithm in Java. My first method

public void populateDijkstraFrom(Node startNode)

creates a Linked List of nodes with its respective distances and predecessors. My second method

public List<Node> getShortestPath(Node startNode, Node targetNode)

is supposed to create a list of nodes with the shortest path from the startNode to the targetNode using the list of nodes from my populateDijkstraFrom method.

However, I don’t know how to access the list of nodes from my Dijkstra method in the getShortestPath method. I could change the return type from void to LinkedList but I was told that it works using void.

How do I do it?

Thanks

There are basically two ways of solving this.

Easiest one would be return the list of nodes on your method

public List<Node> populateDijkstraFrom(Node startNode) {
       // ^ Configure to return list instead of void

    // ......
    return nodeList;
}

public List<Node> getShortestPath(Node startNode, Node targetNode) {
    List<Node> pdList = populateDijkstraFrom(startNode);
    // ^ --- Get the list by simply passing the same parameter to the method
}

Another is stated by Gian

May 15, 2013

I don't know why my variables are getting these values

User1552308’s Question:

public int Gauss_Jordan(double[][] matrix, int numOfRows, int numOfCols) {
    for (int col_j = 0; col_j<numOfCols; col_j++) {
        row_i = nonzeros ++;
        System.out.println(row_i+" and "+nonzeros);
    }
    //return matrix;

    return 0;
}

up above in the method called “Gauss_Jordan”, you can see a for loop where it iterates until a certain condition is met. (duh.. lol sorry).

so i set row_i = nonzeros++ but here’s the thing, when I print out each iteration i get

  • 0 and 1,
  • 1 and 2,
  • 2 and 3

. I would expect the output to be:

  • 1 and 1,
  • 2 and 2,
  • 3 and 3.

How come this is not the case?

If pre-increment is not what you wanted. Check the initialization of nonzeros and change it into ‘1` for it to show up as you want. Your codes are functioning as they should.

March 31, 2013

How to access information from a superclass and subclass?

Question by SkyVar

What I am trying to do is access information (variables, methods, etc) from a superclass and it’s subclasses.

If, what I know about inheritance is right, by accessing the superclass we have access to it’s subclasses by default. So I am thinking that I only need to be able to access the parent (super) class.

But how do I do that?

I am not going to post all the code up here, and that will turn this post into 3 pages.

The superclass is just a general code to create a contact and the class that needs to access the superclass is a class that creates an arraylist and records each contact in the arraylist.

I am not trying to get the code written for me, but all the help to understand how this will work, will be greatly appreciated.

To keep this short, I won’t post the subclasses unless needed.

Contacts (Superclass):

public class Contacts
{
    protected String fname;
    protected String lname;
    protected String email;
    protected String phone;

    public Contacts(String fname, String lname, String email, String phone)
    {
        this.fname=fname;
        this.lname=lname;
        this.email=email;
        this.phone=phone;

    }

    public String getfname()
    {
        return fname;
    }

    public void setfname(String first)
    {
        this.fname=first;       
    }

    public String getlname()
    {
        return lname;
    }

    public void setlname(String last)
    {
        this.lname=last;
    }

    public String getemail()
    {
        return email;
    }

    public void setemail(String e)
    {
        this.email=e;
    }

    public String getphone()
    {
        return phone;
    }

    public void setphone(String num)
    {
        this.phone=num;
    }

    public String getFullName()
    {
        String full=fname+" "+lname;
        return full;
    }

I haven’t done much on this code because I have been trying to figure it out without really knowing where to start. I do not think the arguments should be null, I just included those to satisfy the evil compiler.

Addressbook:

import java.util.ArrayList;
public class AddressBook
{
    Contacts enteredContact = new Contacts(null, null, null, null);
}

Here is one of the subclasses to get an idea of what is included.

Friends (subclass):

public class Friend extends Contacts
{
    private String dob;

    /**
     * Constructs a new Friend object. (Insert any further description that is needed)
     * @param fname
     * @param lname
     * @param email
     * @param phone
     */
    public Friend(String fname, String lname, String email, String phone)
    {
        super(fname, lname, email, phone);
    }

    /**
     * @return the dob
     */
    public String getDob()
    {
        return dob;
    }

    /**
     * @param dob the dob to set
     */
    public void setDob(String dob)
    {
        this.dob = dob;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString()
    {
        return fname+", "+lname+", "+email+", "+phone+", "+dob;
    }

}

Answer by Starx

Use super function/keyword to access parent class. You can call a parent method like this

super.methodName();

To access parent constructor, you can do it in the following way using super() method.

super(null, null, null, null);
March 7, 2013

Checking Array for null element

Question by V1rtua1An0ma1y

So I’ve created my own class with 5 private fields: Each is an array with a pre-set length. It’s my way of creating a table, where each array is a column, and they have pre-set lengths because not every cell will contain an element (So, not using anything dynamic).

Anyway, my question is: Can I check to see if a specific cell of a specific array contains “null”? Using .equals(null) gives a nullpointerexception 🙁

Answer by user000001

When you call .equals(...) you call a method of the object. If it is null, it has no method. Therefore null check like this:

if (myArray[position] == null) {
    ....

}

Answer by Starx

Mixed up for loops and null construct

for(Integer ints : intNum) {
    if(intNum != null) {
      //valid
    }
} 

How do I get specific parts of JSON files for use with HTML?

Question by user2137541

I would like to import JSON data from a file, the code I have at the moment is:

<script>                            
    $.getJSON('data.json', function(data) {             
    var output = "<tr>";
    for ( var i in data.users) {
    output += "<td>"
    + "-- "
    + data.users[i].time
    + " --<br>-- "
    + data.users[i].senderID
    + " --<br>"
    + data.users[i].message
    + "<br></br></td>";
    }
    output += "</tr>";
    document.getElementById("placeholder").innerHTML = output;
    });
</script>

But I can no longer access it as it doesnt get generated with a nice neat name like “users” as you can see below it is “¬í t’” but you cant reference to that as part of it isnt valid characters

    ¬í t’{  
    "messageId": 53,  
    "userTo": {    
    "userId": 4,    
    "userName": "Bob123",    
    "userLastCheckedDate": "Mar 7, 2013 11:14:53 AM"
    },

    "userFrom": {
    "userId": 1,
    "userName": "Joe123",    
    "userLastCheckedDate": "Mar 7, 2013 10:41:44 AM"
    },

    "messageContent": "a lovely message here",
    "messageSentDate": "Mar 7, 2013 11:36:14 AM",
    "messageReadDate": "Mar 7, 2013 12:49:52 PM"
    }

Any ideas? Thanks!

Also, this is the java that generates the JSON

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(userMessages.get(0));
    out.write(json);

Answer by Starx

You can access the object as array too.

for ( var i in data['’ t'']) {

    //.....

}
March 5, 2013

Completing a class definition

Question by user2086204

Suppose that you are given the following PetDriver class, which includes a main method:

public class PetDriver{
  public static void main(String[] args){
    int weight = 40;
    Pet doggie = new Pet("Rover", weight);
    System.out.println("my pet's name is " + doggie.getName());
    System.out.println("my pet's weight is " + doggie.getWeight());
  }
}

Executing main produces the following output:

my pet’s name is Rover
my pet’s weight is 40

My code is as follows but It is returning null.

public class pet {

    public String name;
    public int weight = 40;

    public Pet (String y, int x){
        y = name;
        x = weight;
    }

    public String getName(){
        return name;
    }

    public int getWeight(){
        return weight;
    }
}

Thanks!

Answer by Starx

Your constructor does not assign the value to the properties. Change them to the following.

public Pet (String y, int x){
  name = y;
  weight = x;
}
March 3, 2013

how to add random number to an array

Question by Lish

This is classwork. I’ve been reading and searching and everything is telling me to use the java.util.Random of which I understand how that works and wish I could use it. but my assignment specifically tells me to use the (int) (Math.random * number) of which I am having difficulty seeing where to apply into my array. everything I’ve seen has been the Random pulled from java.
It is the generate 100 random integers 0-9 and how many times they occur. If someone can assist?
My error is – Exception in “main” java.lang.array index out of bounds exemption:10 and obviously there is something in my code wrong too.

public class NumberOfTimes{

  public static void main(String[] args){

    int rand = (int)(Math.random() * 10);
    int[] counts = new int [10];

    for(int i = 0; i < 100; i++){

      counts[i]++;
    }//end for

    System.out.println("numbert" + "occurence ");

    for (int num = 0; num < counts.length; num++){

      System.out.println(num + "t" + counts[num]);
    }//end for

  }//end main

}//end NumberOfTimes   

Answer by Evgeniy Dorofeev

make this change

int[] counts = new int[100];
for (int i = 0; i < 100; i++) {
    counts[i] = (int) (Math.random() * 10);
}// end for

Answer by Starx

Your array can only hold 10 items, and on your loop you are accessing more than 10. Can be solved in two ways.

  • Either Increase your array length

    int[] counts = new int [100];
    
  • Or either decrease your count in for loop.

    for(int i = 0; i < 10; i++){
    
November 1, 2012

Extacting words between $ symbol

Question by rajesh

I want to extract the words between the symbol $.

String = " this is first attribute $color$. this is the second attribute $size$"

I want to get a string list as List =[color , size]

I have used

Pattern pattern = Pattern.compile("(\$) .* (\$)");
Matcher matcher = pattern.matcher(sentence);

but I get the out put as

"$color$.this is the second attribute $size$"

please help me to solve this problem

Answer by halex

The problem is that the regex you are using is greedy and consumes everything beginning at the first $ until the last $ in your string. You have to add a ? after the * to make the regex nongreedy:

Pattern pattern = Pattern.compile("\$(.*?)\$");
Matcher matcher = pattern.matcher(sentence);
List<String> result = new ArrayList<String>();
for(int i=1; i <= matcher.groupCount(); i++)
    result.add(matcher.group(i);

Answer by Starx

Try this regex. It should give what is expected.

Pattern pattern = Pattern.compile("$(.*?)$");
...

Please fill the form - I will response as fast as I can!