Assistance with a very basic Java Application (semi-Urgent)?

  • Thread starter Eric.
  • 12 comments
  • 2,062 views

Eric.

Premium
8,515
GTP_Eric
Ebiggs
Before anyone points it and and tries to derail the thread, yes this is a homework assignment. However, all the code is there, I'm just lost as to what is keeping it from compiling.

The application is to write a method isMultiple that takes in two integers, determines if the second integer is a multiple of the first, and then outputs true or false accordingly. I've spiced it up from just using the console to using JOptionPane for dialog boxes, which wasn't necessary but I need to vary things from the old System.out and Scanner crap. No problem figuring out any of the algorithms or anything like that. Problem is that the method has to be inside of an application, so its not just running the code for that under the main method.

Before I go any deeper, I'll post the code.

Code:
//
//
//
//
//

// Java application utilizes JOptionPane for user input
// of two integers, then determines if the second integer
// is a multiple of the first.  The result is shown to the
// user in another JOptionPane dialog.

import javax.swing.JOptionPane;

public class Multiples
{
    public static void main( String[] args )
    {
        // declare variables
        int firstInt = 0; // first integer input from user
        int secondInt = 0; // second integer input from user
        String firstNumber = "0"; // value read from JOptionPane
        String secondNumber = "0"; // value read from JOptionPane        
        
        // JOptionPane prompts user for integers and
        // stores them accordingly
        
        firstNumber =
            JOptionPane.showInputDialog( "Enter the first integer" );
            
        secondNumber = 
            JOptionPane.showInputDialog( "Enter the second integer" );
            
        // convert to integers
        
        firstInt = Integer.parseInt ( firstNumber );
        secondInt = Integer.parseInt ( secondNumber );
        
        
            
        // determination
        public static void isMultiple()
        {
            // messages
            String messageTrue = secondInt + " is a multiple of " + firstInt +
                "\n" + firstInt + " * " + secondInt + " = " + (secondInt / firstInt);
            String messageFalse = secondInt + " is not a multiple of " + firstInt;    
            
            if ( secondInt % firstInt == 0 )
            {
                JOptionPane.showMessageDialog( null, messageTrue );
            }
            else
            {
                JOptionPane.showMessageDialog( null, messageFalse );
            }
            
        } // end isMultiple
} // end main
} // end class Multiples
And when compiling, I get this error message (compiled in jGRASP):

Code:
 ----jGRASP exec: javac -g E:\School\2009-2010 Fall\CSCI 1104\Projects\Chapter 7\6.16 Multiples\Multiples.java

Multiples.java:41: illegal start of expression
        public static void isMultiple()
        ^
Multiples.java:41: illegal start of expression
        public static void isMultiple()
               ^
Multiples.java:41: ';' expected
        public static void isMultiple()
                     ^
Multiples.java:41: ';' expected
        public static void isMultiple()
                                       ^
4 errors

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

So I obviously don't know how to declare a method within main. Any help? I played around for quite a while with it and got nothing better than this. I did try ending the main codeblock before I declare isMultiple, but then I have to move all of the variables and pretty much everything that is in main over to isMultiple, which I really don't think is right. And I know its possible to do it this way, somehow.

I'd appreciate any advice!
 
I know absolutely nothing about coding Java so just say no and move on, unless by some miracle I'm correct.

Should it be

Code:
        // determination
        public void isMultiple()
instead of
Code:
        // determination
        public static void isMultiple()
A site I was looking at has only one static void for the main and the other one is just a void.

Whatever all of that means. :lol:
 
I tried just about every combination of public, static, and void there and it always gave the same error.

Thanks though. :)
 
It was worth a shot. Staring at code trying to figure out a problem is a pain in the butt (based solely off of my HTML experience). Made worse when a fresh set of eyes spots the problem right away. Not the case this time, but coming from me that's not surprising. :P

Good luck, Eric.
 
I don't think Java supports method definitions within an existing method, which would explain the compilation errors.

What's stopping you from defining isMultiple(int one, int two) from outside main and passing in the two input numbers to that method? Or are you not allowed to do it that way - by calling a custom method from inside main?

Something like this:
Code:
import javax.swing.JOptionPane;

public class Multiples
{
    public static void main(String[] args )
    {
        // declare variables
        int firstInt = 0; // first integer input from user
        int secondInt = 0; // second integer input from user
        String firstNumber = "0"; // value read from JOptionPane
        String secondNumber = "0"; // value read from JOptionPane        
        
        // JOptionPane prompts user for integers and
        // stores them accordingly
        
        firstNumber =
            JOptionPane.showInputDialog( "Enter the first integer" );
            
        secondNumber = 
            JOptionPane.showInputDialog( "Enter the second integer" );
            
        // convert to integers
        
        firstInt = Integer.parseInt ( firstNumber );
        secondInt = Integer.parseInt ( secondNumber );
        
        [B]isMultiple(firstInt, secondInt);[/B]
            
        
} // end main
       [B] public static void isMultiple(int firstInt, int secondInt)[/B]
        {
            // messages
            String messageTrue = secondInt + " is a multiple of " + firstInt +
                "\n" + firstInt + " * " + secondInt + " = " + (secondInt / firstInt);
            String messageFalse = secondInt + " is not a multiple of " + firstInt;    
            
            if ( secondInt % firstInt == 0 )
            {
                JOptionPane.showMessageDialog( null, messageTrue );
            }
            else
            {
                JOptionPane.showMessageDialog( null, messageFalse );
            }
            
        } // end isMultiple
} // end class Multiples
 
It's not a big deal anyway, the instructor will probably help me out. He'll be happy to see JOptionPane in there instead of plain console messages.
 
I don't think Java supports method definitions within an existing method, which would explain the compilation errors.

What's stopping you from defining isMultiple(int one, int two) from outside main and passing in the two input numbers to that method? Or are you not allowed to do it that way - by calling a custom method from inside main?

Something like this:
Code:
import javax.swing.JOptionPane;

public class Multiples
{
    public static void main(String[] args )
    {
        // declare variables
        int firstInt = 0; // first integer input from user
        int secondInt = 0; // second integer input from user
        String firstNumber = "0"; // value read from JOptionPane
        String secondNumber = "0"; // value read from JOptionPane        
        
        // JOptionPane prompts user for integers and
        // stores them accordingly
        
        firstNumber =
            JOptionPane.showInputDialog( "Enter the first integer" );
            
        secondNumber = 
            JOptionPane.showInputDialog( "Enter the second integer" );
            
        // convert to integers
        
        firstInt = Integer.parseInt ( firstNumber );
        secondInt = Integer.parseInt ( secondNumber );
        
        [B]isMultiple(firstInt, secondInt);[/B]
            
        
} // end main
       [B] public static void isMultiple(int firstInt, int secondInt)[/B]
        {
            // messages
            String messageTrue = secondInt + " is a multiple of " + firstInt +
                "\n" + firstInt + " * " + secondInt + " = " + (secondInt / firstInt);
            String messageFalse = secondInt + " is not a multiple of " + firstInt;    
            
            if ( secondInt % firstInt == 0 )
            {
                JOptionPane.showMessageDialog( null, messageTrue );
            }
            else
            {
                JOptionPane.showMessageDialog( null, messageFalse );
            }
            
        } // end isMultiple
} // end class Multiples

Hm, thanks. That might work. Its a little late for me to be looking at code, so I'll give it a shot tomorrow and check back. :cheers:
 
I tried just about every combination of public, static, and void there and it always gave the same error.

Thanks though. :)

Let me clarify the uses of those keywords a bit:

Static means it's a method or attribute that can be called/accessed without instantiating the class. E.g. you can just call a static method by using
Code:
ClassName.doSomething()
You can access a static attribute like that too. The Integer.parseInt(..) method is a good example of a static method, you just call it on the class, not on an instance.

If a method or attribute is not static, you have to create an instance of the class first:

Code:
MyObject m = new MyObject();
m.doSomething();
void is just the return type of the method. void means the method returns nothing. If you have a method that returns, let's say a boolean, it would read
Code:
boolean doSomething()
public is a visibility modifier. public means it can be accessed by any other class. protected means it can be accessed by other classes, but only in the same package. private means it can only be accessed by instances of the same class.

So when you have a method that starts with 'public static void' it means it's a method that can be called from anywhere, can be executed without instantiating the class and does not return anything.

I don't think Java supports method definitions within an existing method, which would explain the compilation errors.
Correct, it will not. You can, however, define classes within classes.

Combining the above, you could write a simple method that returns true or false like below. Then have a seperate method that calls this one and makes up the message. By doing it this way, you can have seperated the calculation from the presentation, allowing you to reuse the calculation in another application (which is what you want/must do right?)

Code:
[B]public static boolean isMultiple(int firstInt, int secondInt)[/B]
        {
            return ( secondInt % firstInt == 0 );
        } // end isMultiple
 
On the iPhone, so I'll keep this short...


Thanks NL, I do know what the keywords do. I was just trying to troubleshoot really.

But while I've got this thread going, would you care to explain the purpose of using set and get functions? When we've used them it seemed like the long way to just say
Code:
variableName = name

Whatever app we used it in just took In parameters from a method call and seems to really just set variable names and then insert them wherever necessary.
 
Well, it's a good coding practice to use local variables where possible instead of instance variables. This makes thread-safety less of an issue if you're working on code that is used in a multi-threaded environment (like a web app).

Getters and setters are used to hide the implementation details of instance variables from callers (encapsulation). E.g. you define a property as 'private', then create a public setter/getter for it. That way, you can change the implementation details of the property (e.g. change the 'internal' type) or do additional required stuff when the property is set (e.g. validations, updating references to other classes, throw an exception if certain rules are being violated, get stuff from a database or other resources, etc.).

And you can do so without having to recompile other classes calling these methods, since you have encapsulated that behavior behind a method.

It's a good practice to keep the inner workings of a class to itself and just provide an interface for other classes to call/use.

Here's a little example: I have two classes 'MyParentClass' and 'MyChildClass'. Both child and parent have a reference to eachother (e.g. the relationship is bidirectional). That means that at least one of them should maintain the relationship both ways (you can't do it on both sides or you'll get an infinite loop ;)). In this case, the parent has some additional functionality inside the setter to maintain the bidirectionality of the relationship.

Code:
public class MyChildClass {

	private MyParentClass myParentClass;

	public MyParentClass getMyParentClass() {
		return myParentClass;
	}

	public void setMyParentClass(MyParentClass myParentClass) {
		this.myParentClass = myParentClass;
	}
	
}

Code:
public class MyParentClass {

	MyChildClass myChildClass;

	public MyChildClass getMyChildClass() {
		return myChildClass;
	}

	public void setMyChildClass(MyChildClass myChildClass) {
		this.myChildClass = myChildClass;
		[B]myChildClass.setMyParentClass(this);[/B]
	}
	
}
 
Last edited:
That worked just fine Sharky. I ended up using your changes. One of the other projects that was also due today just determined whether an integer was even or not, so all that was required was to remove anything about a second integer and just a few other modifications. 👍
 
Glad it worked 👍 (of course, I knew it would :P)

But while I've got this thread going, would you care to explain the purpose of using set and get functions?
Setters and getters work with the key programming principle of only making public what is absolutely necessary.

Yes, you could make every single variable you're using public, and that's perfectly legal, but it can cause problems if you accidentally lose track of what each variable represents and you store a value in the wrong variable. Setters offer protection from this by forcing you to explicitly call a method to change the value of a variable - and if you use setter methods you can do additional stuff when the setter is called (a setter doesn't have to solely change the value of a variable, it can call other functions and methods and have loops etc in it). Example: someObject.setSomeVariable(toThisValue)

Getters work along the same train of thought - if you had everything public without any setters and getters, and wanted to store the value of "someVariable1" from some class A - let's assume you have an object called Eric of type A - into a variable local to the current class "someVariable2", both Eric.someVariable1 = someVariable2 and someVariable2 = Eric.someVariable1 would be legal, and would compile without warnings. Therefore you could put the variables on the wrong side of the statement and not notice until you get weird results at runtime.

However, if you made someVariable1 private and only allowed access through getters and setters, someVariable2 = Eric.someVariable1 - storing value of someVariable1 into someVariable2 - would not compile (error along the lines of someVariable1 has private access in Eric) - the only way to perform this assignment without a compilation error would be someVariable2 = Eric.getSomeVariable1(). As you can see, it is a lot easier to spot when you've mixed up your assignment statements.

So, in a nutshell, getters and setters offer protection from accidentally (or otherwise) mixing up your assignments and whatnot.


NLx, feel free to correct/agree with whatever is necessary :P
 
NLx, feel free to correct/agree with whatever is necessary :P
You're absolutely right, besides being a good OO principle it also helps against bugs. :)

There is an exception to the rule though: constants. These are usually exposed directly as a property, and not through getters (and, being constants, you can't set them ;)). The Color class is a good example where constants are used. E.g. you can just reference the color black by using Color.BLACK.
 
Back