tux4life 2,072 Postaholic

my doubt is that right after his constructor, he has a ; which shouldn't be there.

While it doesn't seem to be generally used, it is valid syntax.
As I implied by my previous post there's nothing wrong with it since it compiles perfectly.
You could argue that it might be a bug in the compiler, but I will support my statement by quoting the relevant section(s) of the Java Language Specification:

ClassMemberDeclaration:
        FieldDeclaration
        MethodDeclaration
        ClassDeclaration                        
        InterfaceDeclaration
        ; // semicolon is a valid ClassMemberDeclaration

(Source: JLS - 8.1.6 Class Body and Member Declarations)

Therefore you could write syntactically valid code like:

public class Test
{
    private int a;

    public Test(int a)
    {
        this.a = a;
    };; // [1]

    public int getA()
    {
        return a;
    }; // [1]

    public static void main(String[] args)
    {
        System.out.println(new Test(15).getA());
        ;;;;;; // [2]
    }; // [1]
}; // [3]

; // [3]
; // [3]
; // [3]
 ;;;; ;; // [3]

class B
{
}

Lines marked by a [1] are valid as of: JLS - 8.1.6 Class Body and Member Declarations)

ClassMemberDeclaration:
        FieldDeclaration
        MethodDeclaration
        ClassDeclaration                        
        InterfaceDeclaration
        ;

Lines marked by a [2] are valid as of: JLS - 14.6 The Empty Statement

EmptyStatement:
        ;

Lines marked by a [3] are valid as of: JLS - 7.6 Top Level Type Declarations

TypeDeclaration:
        ClassDeclaration
        InterfaceDeclaration
        ;
tux4life 2,072 Postaholic

Here's a readability tip: use constants defined in the KeyEvent class.

Example:

if (e.getKeyCode() == KeyEvent.VK_UP) {
    // ...
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    // ...
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    // ...
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    // ...
}
tux4life 2,072 Postaholic

I don't get any compiler error when trying to compile the piece of code that you've posted.
Please post the piece of code that results in the compiler error you've described.

tux4life 2,072 Postaholic

Minor correction on my previous post:

"Prefer not using wildcards and importing by specifying the fully qualified classname."

should be:

"Prefer not using wildcards and - instead - import by specifying the fully qualified classname."

tux4life 2,072 Postaholic

In addition to what's been said, my opinion is that you should prefer to not have unused import statements in your code. (Not that it will differ in terms of performance though).
Also my preference is that you specify exactly which class you want to use instead of using the asterisk wildcard.
The reason for this is that by importing per class you don't pollute the namespace you are using with names that you don't use, plus it is easy to see which classes are actually used by the code that follows.

Also, because different packages can contain classes with the same names, by importing the whole package you can run into a compiler error if you try to use a class which exists in both packages by not using its fully qualified class name.

A good example of this can be found in the Java API: java.util.List and java.awt.List.

Suppose you have code written like:

import java.util.*; // this package contains a class List
import java.awt.*;  // this package contains a class List too

// ...

// We want to use java.util.List here
List<Component> names; // will result in a compile-time error [1]

[1]

error: reference to List is ambiguous, both class java.awt.List
in java.awt and interface java.util.List in java.util match
        List d;
        ^
1 error

Rather do something like:

import java.util.List;     // import by specifying fully qualified classname
import java.awt.Component; // we also need the Component class …
tux4life 2,072 Postaholic

What you provided is great but not really portable.

How is a digital version of the standard "not really portable"?

Edit: Take a look here.

tux4life 2,072 Postaholic

What is the download link and where did you get it from?

tux4life 2,072 Postaholic

You probably declared your faceCombo something like:

JComboBox faceCombo = new JComboBox();

Even though it will work, you used a raw type: JComboBox can take a type parameter that specifies what the type is of the items you want to put in it.

From the code snippet you posted it seems like you want to put items of type String in your combo box, so you'll want to specify String as argument to the type parameter, as follows:

// Pre Java 7:
JComboBox<String> faceCombo = new JComboBox<String>();

// Since Java 7 you can also use diamond syntax to let the compiler
// infer the type on the right hand side.
JComboBox<String> faceCombo = new JComboBox<>();

So, what does this stuff really mean?

If you write

JComboBox faceCombo = new JComboBox();

it is equivalent to specifying Object as type argument:

JComboBox<Object> faceCombo = new JComboBox<Object>();

In Java every class either directly or indirectly and explicitly or implicitly extends class Object.
That means that if you have Object as type argument you can really put every object in it.
If you are not careful, and somewhere in your code you'd accidentally add an object of type Integer in it, then your combo box model will contain objects of two different inheritance trees (only having Object as supertype in common).

// implicitly Object is the argument to the type parameter, DON'T DO THIS
JComboBox faceCombo = new JComboBox();

// the following is …
tux4life 2,072 Postaholic

You're getting an ArrayIndexOutOfBoundsException because you are trying to access indexes that are not valid in your array.
The array you are iterating over is smaller than 10 elements, yet you are adding 10 to every i, which is guaranteed to be out of bounds for any i >= 0.

Instead of: numbers[i+10] you probably intended: numbers[i].

tux4life 2,072 Postaholic

Amazon

tux4life 2,072 Postaholic

Quick example:

// Fetch member entity of Dani
Member dani = RequestBuilder.memberRequest().username("dani").build().fetchSingle();

// Fetch Java code snippets by Dani and order them last post first
FetchRequest<Article> request = RequestBuilder.articleRequest()
    .members(dani.getUserId())
    .forums(9)
    .orderBy(LASTPOST)
    .filter(CODE)
    .build();

List<Article> articles = request.fetchMultiple();

// Fetch Forum data of the C/C++/Java forums
List<Forum> forums = RequestBuilder.forumRequest().ids(118, 8, 9).build().fetchMultiple();
tux4life 2,072 Postaholic

I've been working on a Java API that tries to simplify accessing the Daniweb API from Java based applications.
It isn't finished yet and still has bugs. I attached to my post what's basically an export of my Eclipse project.
I release it because at the moment I lack the time to finish the implementation and because there doesn't seem to be alot of Java activity around the Daniweb API.
I hope the release of this source will encourage the Java people to experiment with Java and the Daniweb API.
Later when I will have time to finish it I'll clean it up and post it down as a code snippet.
Any suggestions, fixes and constructive critique are always welcomed and highly appreciated. ;)

tux4life 2,072 Postaholic

You can make use of the left shift operator: <<.

2^2 = 2 << 1
2^3 = 2 << 2
2^4 = 2 << 3
etc.

It works as follows: the decimal number 2 can be represented in binary as 00000010.
The << operator shifts all the bits to the left by the number of positions specified by its right operand. So:

  Java  |                 |  Binary outcome  |  Decimal  |  2^n
------------------------------------------------------------------
 2 << 1 |  00000010 << 1  |    00000100      |     4     |  2^2
 2 << 2 |  00000010 << 2  |    00001000      |     8     |  2^3
 2 << 3 |  00000010 << 3  |    00010000      |    16     |  2^4

Edit: This will cause overflow for large n, highest power I was able to get without overflowing, is: 2^62 using long.

tux4life 2,072 Postaholic

Actually to be correct, the Color constructor we're talking about takes 3 values in the range 0-255 (255 inclusive!)

Thus, to be entirely correct you'd need to call the constructor as follows:
new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256))

How do I return just int numbers I can use somewhere else?

You could use the getRed, getGreen and getBlue methods of the Color class and pass around Color objects.

So the problem I am having here is that after having run the program everytime I resize the java windows the shapes get drawn again, whereas I'd like them to stay as they are. Is that possible?
...
thanks...wouldn't have a clue how to save the shapes sorry : -)

Not required by the exercise, however, you can store your shapes in an ArrayList and in your paintComponent draw every shape in the list.

tux4life 2,072 Postaholic

Perhaps a redundant question: is it also fixed for member usernames?
Or does the registration process prevent users from putting HTML in their nicknames?
Edit: What about a user that does a name change?

tux4life 2,072 Postaholic

This issue is easiest explained by a screenshot:

rmas_screenshot

The title of the thread linked to contains the <input> starttag: Help on clear text in <input> !!.
I'm wondering what would happen if someone inserted an <img> tag in a thread title...

Edit: Perhaps the solution is not to strip them, but to convert them so that they are not parsed as HTML.
Edit: This is reproducable by opening the thread I linked to while having the activity stream opened in another tab.

~s.o.s~ commented: Nice find +0
tux4life 2,072 Postaholic

Print the options the user can choose from, and prompt the user to choose one of them.
Without error checking the code could look as follows:

System.out.println("1 = add, 2 = subtract");
System.out.println("pick an option> ");
int choice = Integer.parseInt(input.nextLine());
// ...
tux4life 2,072 Postaholic

I have the above code and its thorwing an exception of numberformatException. What is wrong with this code .. kindly help me out.

Which values did you enter as input?

Edit: look closely at the following two lines of code:

String s = ("1= add, 2 = subtract");
int op = Integer.parseInt(s);

You are trying to parse the String 1= add, 2 = subtract as an int, and then get thrown a NumberFormatException in your face because that String is not a valid number.

tux4life 2,072 Postaholic

What Should I put in "paramètre 1", "paramètre 2"

It's in the library documentation:

An argument list for the invoked method or constructor.
This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked.
If there are no parameters, parameters should be null.

(Source: MethodBase.Invoke)

Here's an example that demonstrates a reflective method call to a method with no parameters:

using System;
using System.Reflection;

public class Test
{
    public static void Main(string[] args)
    {
        Type typeOfB = typeof(B);
        object obj = Activator.CreateInstance(typeOfB);
        MethodInfo methodToCall = typeOfB.GetMethod("myMethod");
        // null is passed as second argument because "myMethod" does not have parameters
        methodToCall.Invoke(obj, null);
    }
}

public class A
{
    public void myMethod()
    {
        Console.WriteLine("myMethod called");
    }
}

public class B : A
{}

// output:
// myMethod called

The example is mostly analog to your problem so you should be able to adapt it to your problem quite easily.

ddanbe commented: Great effort, as always! +14
tux4life 2,072 Postaholic

Convert spaces to %20 as so

That fixes it. Thank you :)

It is by design that URLs get URLified within code.

However this post first inline code box doesn't URLify the whole link. As you can see the '(T...)' part is not URLified. How is that done then?
Also that makes me wonder why a valid URL such as
'http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#pow(double,%20double)'
or
'http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)'
doesn't get URLified as a whole automatically?

tux4life 2,072 Postaholic

I've reopened this question because of another issue that I'm facing.

In this post the URL doesn't get rendered correctly. I checked using a different browser with cleared cache.

I wrote the text "Math.pow", selected it, clicked the Link button, and pasted there the copied URL:
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#pow(double, double).

Result:
[Math.pow](http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#pow(double, double))

Also it feels unpleasant that a URL gets URLified when marked as inline code.

I use Pale Moon 15.4.1-x64 and Chrome 24.0.1312.57 m.

tux4life 2,072 Postaholic

Exact error message (when compiling from the command line):

C:\Users\mvmalderen\Desktop>javac Calculator.java
Calculator.java:31: error: ')' expected
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                       ^
Calculator.java:31: error: illegal start of expression
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                           ^
Calculator.java:31: error: ';' expected
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                               ^
Calculator.java:31: error: not a statement
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                ^
Calculator.java:31: error: ';' expected
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                 ^
Calculator.java:31: error: not a statement
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                  ^
Calculator.java:31: error: ';' expected
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                   ^
Calculator.java:31: error: not a statement
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                     ^
Calculator.java:31: error: ';' expected
            case 2: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                      ^
Calculator.java:33: error: ')' expected
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                       ^
Calculator.java:33: error: illegal start of expression
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                           ^
Calculator.java:33: error: ';' expected
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                               ^
Calculator.java:33: error: not a statement
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                ^
Calculator.java:33: error: ';' expected
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                 ^
Calculator.java:33: error: not a statement
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                  ^
Calculator.java:33: error: ';' expected
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                   ^
Calculator.java:33: error: not a statement
            case 3: A = (P *(1 + (r/n))Math.pow(n,t)-P);
                                                     ^
Calculator.java:33: error: ';' expected
            case 3: A …
tux4life 2,072 Postaholic

If you want to use an integer as a key in a Map you'll need to use a primitive wrapper.

Here's an example of that:

Map<Integer, String> map;

Note that the following is not valid:

Map<int, String> map; // invalid
tux4life 2,072 Postaholic

first create jsp page and insert your database code into it.also post what you have done so far...

You should NEVER write business and persistence logic directly inside a JSP page.
Take a look at: JSP database connectivity according to Model View Controller (MVC) Model 2.

tux4life 2,072 Postaholic

I think the OP wants to know how to do a reflective method call.

tux4life 2,072 Postaholic

Esso

tux4life 2,072 Postaholic

When quoting a user, the username of the quoted user isn't shown.
The page about markdown syntax seems to imply that this isn't possible in a syntax supported way.
I think it would contribute to clarity to also be able to syntactically specify the username of the quoted user.
I remember that years ago (before introducing markdown syntax) it was possible to do this.
Is there any reason as to why the option to specify the quoted user isn't included anymore nowadays?

I know we can write something like what's below, but if it were supported in the syntax, it could be displayed in a standard way.

username:

quoted message

tux4life 2,072 Postaholic

riahc, I can't run your program because it says I don't have the latest version of .NET. Plus, I'm on a mac.

Here are screenshots of riahc's C# application:

main_window

postcount_dialog

tux4life 2,072 Postaholic

Please post your whole code, so that I can reproduce the error.

tux4life 2,072 Postaholic

Could you post the error message?
Also, a readability tip: define three constants

final int SHOW   = 1;
final int INSERT = 2;
final int DELETE = 3;

Then you could (re)write your if statements like:

if (task == SHOW) {
    // ...
}
else if (task == INSERT) {
    // ...
}
else if (task == DELETE) {
    // ...
}

This will also work with the switch statement I referred to in an earlier post.

tux4life 2,072 Postaholic

I can't remember that I've ever had the ability to change it. And if I've had the ability at some point in time, I can assure you that I never made a change to my user title.

tux4life 2,072 Postaholic

If I do the following GET request:
http://www.daniweb.com/api/members?username=mvmalderen
My usertitle in the result is 'Postaholic', while everywhere on the website it is shown as 'Posting Maven'.

tux4life 2,072 Postaholic

The API doesn't seem to allow in giving a vote with comment.

tux4life 2,072 Postaholic

An important thing, not directly related to your question, but related to connecting to databases from an application in general is that you shouldn't hard-code the connection details into the application.
It would be an improvement to store the database connection parameters in say, a configuration file, for example.

tux4life 2,072 Postaholic

Do you have a specific question about this piece of code? Or was this intended to be a code snippet?

tux4life 2,072 Postaholic

I have problems with it. I can't display number and characters properly.

How did you try displaying them?

// this should be the character input

Why do you want a name to be a single character anyway? A name usually consists of more than one character, right?
If you really want to have one single character, then read the whole line, and pick-off the first character using charAt(0), as suggested in my first reply.

I have a code that goes like this:

You're on the right track, your next step would be adding insert and delete operations.

I don't know the proper code for inserting a new element in a string and delete an existing element..

Don't forget that in Java Strings are immutable, you can't insert/delete "elements" in it.
What you probably meant is inserting and removing a new element in a list of Strings?
Take a look at the Java API documentation for the ArrayList class.
Notice that ArrayList has methods such as add and remove. They are even overloaded.
For the overloaded versions, I refer to the API docs for the ArrayList class, but you probably won't need those for this program.

tux4life 2,072 Postaholic

You should run PetTest [1] instead of Pet.
If you're on the command line this means that you have to invoke as: java PetTest (after compiling).

Also you have to remove what's on line 11, its syntax is invalid.

[1] Because this class contains the main method.

tux4life 2,072 Postaholic

Arrays.sort(int[]) should do the job.

tux4life 2,072 Postaholic

is Char.parseChar(inp.readLine()); a right line to get the char of user's input?

Nope, in fact, it doesn't even exist. Read my first reply.

When I tried to do either private String[] employees; { or public String[] employees; { , I can't call it properly on the output. How can I call the whole list in the output?

Read my first reply (the part about the Arrays utility class).
Note that if you're using an ArrayList you don't need to keep a separate array reference.
You should decide which approach to go with, either you write your own list implementation, or you reuse an existing one (such as ArrayList) from a class library (such as Java's class library).

It might be a good idea to check with your instructor which classes from the Java API you are allowed to use.
(e.g. are you allowed to use java.util.ArrayList? java.util.Arrays?)

tux4life 2,072 Postaholic

what should goes first? private String employees[] or public static void main (String args[]) throws Exception?

Seems like you chose to use ArrayList after all. In that case you don't need to keep a separate array reference.
Also it doesn't matter which one goes first, whether you first put your fields, then your methods, or first the methods and then your fields, or put fields between methods. It's all valid.

tux4life 2,072 Postaholic

I'm writing this post for everyone who - like me - is trying to send requests with: Content-Type: application/json.

I figured it out the hard way (by capturing the packet sent from the PHP code sample) that the Content-Type needs to be multipart/form-data.

tux4life 2,072 Postaholic

Because, I will just use Integer.parseInt for the input.
Then, I'll use if-else statement to justify the user's choice.
Plus, I don't know if it would work under if-else statement..

Sounds workable to me. Alternatively you could use a switch statement.
Try it and when you encounter problems post what you tried so that we can take a look and suggest a way to fix it.

tux4life 2,072 Postaholic

But I still don't understand some parts.. like "private".

Take a look here.
Basically the idea is that the employees array reference should not be exposed.
Compare the following two approaches:

1) Marking it public or default:

// Marking it public
public class EmpList
{
    public String[] employees; // accessible from everywhere

    // ...
}

// Marking it default
public class EmpList
{
    // default access is what you get by "default" when you don't
    // specify 'public', 'private' or 'protected'
    String[] employees; // not accessible from everywhere, but still
                        // accessible from everywhere in the package of
                        // your EmpList class.

    // ...
}

Somewhere else in your code (outside the EmpList class) it is now possible to write this:

EmpList list = new EmpList();
employees.add("John");
employees.add("Tom");
employees.add("Abbey");
list.employees = null; // this would be VERY BAD, after executing,
                       // the elements in EmpList are "gone".

2) Marking it private:

public class EmpList
{
    private String[] employees; // only accessible from inside EmpList

    // ...
}

Somewhere else in your code (outside the EmpList class) you might try writing this:

EmpList list = new EmpList();
employees.add("John");
employees.add("Tom");
employees.add("Abbey");
list.employees = null; // will cause a compiler error because
                       // the employees field is marked as 'private',
                       // none of the employees is gone.

Because you've marked the employees field as private this is not possible - which is a good thing.
Imagine the bugs …

tux4life 2,072 Postaholic

Do you need to write your own simple list implementation as an assignment?

If so, then you'll need to work on your EmpList class, because as it stands now it is no better than using an array directly.
You should encapsulate your implementation and mark your employees array reference in EmpList as private.
Furthermore you should provide a public interface (don't confuse this with a Java interface) that contains methods for:

  • querying the size,
  • adding an element,
  • removeing an element,
  • getting an element by index

Think of something you could use like this:

// Create an empty list
EmpList employees = new EmpList();

// Adding elements
employees.add("John");
employees.add("Tom");
employees.add("Abbey");

// Removing elements
employees.remove("Tom");

// Iterating
for (int i = 0; i < employees.size(); i++)
    System.out.println("Employee #" + i + " = " + employees.get(i));

// Expected output:

// Employee #0 = John
// Employee #1 = Abbey

our instructor told us to use j2sdk 1.4.2_14

Why would you stick with something old like that?

I figured out that some of the package files like.. java.util.Scanner were not included in it.

That is because the Scanner class was new in Java 5.

tux4life 2,072 Postaholic

Use the escape sequence: '\\'.

Example:

char c = '\\'; // store a backslash
jalpesh_007 commented: good solution.. +4
tux4life 2,072 Postaholic

Cisco

tux4life 2,072 Postaholic

Don't hardcode the length of your array:

// DON'T do this
for(int k = 0; k < 5; k++)
    System.out.println(employees[k]);

instead use the array's length field:

// DO this instead
for(int k = 0; k < employees.length; k++)
    System.out.println(employees[k]);
tux4life 2,072 Postaholic

[line 18]: // I got a problem with this here. It's supposed to be a command that reads a char input. But I don't know how to do it too.

You can pick-off the first character in the String. readLine() returns a String, and the String class has a method charAt().
So you can do: inp.readLine().charAt(0).

The line System.out.println(employees[]); has invalid syntax: the brackets aren't allowed there unless you specify an index.
From context I'd say that you probably intended: employees[k].

Another option is to make use of the Arrays utility class to get a String representation of your array.
Here's an example of how you can do that: Arrays.toString(employees), as you can see: you don't have to write a loop.

Do you want/have to write your own list class that is backed by an array and provide insert and delete operations for it? If not, then use ArrayList.

tux4life 2,072 Postaholic

SAP

tux4life 2,072 Postaholic

What you refer to as "ternary expression" is actually called the conditional operator in Java.
Terminology aside, you can use the conditional operator as a shorthand for the following:

int a;

if (condition)
    a = expression1;
else
    a = expression2;

Using the conditional operator, the above can be rewritten as follows:

int a = condition ? expression1 : expression2;

For more precise info about what condition, expression1, and expression2 can be, I refer to the Java Language Specification section 15.25 Conditional Operator ? :.