Using Consecutive Method Calls On A Single Object

Mar 24, 2014

I don't remember where but I faintly recall one of the oracle docs examples (dealing with GUI basics I think) having something similar to

button.add(lbl).addIcon().addActionListener(al);

but only in the aspect of using .method.method.method

The reason I'm asking is because I want to shorten this

int j = 0;
for(int i = 0; i <= 6; i+=3){
pnl[j+2].add(lbl[i+5]);
pnl[j+2].add(lbl[i+6]);
pnl[j+2].add(drop[j]);
pnl[j+2].add(lbl[i+7]);
pnl[j+2].add(btn[j]);
j++;
}

Into something like this

int j = 0;
for(int i = 0; i <= 6; i+=3){
pnl[j+2].add(lbl[i+5])
.add(lbl[i+6])
.add(drop[j])
.add(lbl[i+7])
.add(btn[j]);
j++;
}

I might be way off though... but I'm just wondering under what circumstances would this be possible

When I try it in Eclipse a little notification appears that says...

"The method add(PopupMenu) in the type Component is not applicable for the arguments (JLabel)"

When I google 'Component' I see it appears to have something to do with Serialization (which I'll need to look into)

View Replies


ADVERTISEMENT

Altering Parent Method Behavior By Overriding Method It Calls

Apr 21, 2014

I have two classes (Daughter and Son) that contain some very similar method definitions:

public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();
d.speak();
s.speak();

[Code] .....

Each of those classes has a "speak" method with two out of three lines being identical. I could move those into a parent class, but I need each of the child classes to continue to exhibit its unique behavior. I'm trying the approach below, which replaces the unique code with a call to a "placeholder" method that must be implemented by each child class:

public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();

[Code] .....

This works and moves the shared code from two places (the Daughter and Son classes) into one place (the new Mother class, which is now a parent class of Daughter and Son). Something about this feels a bit odd to me, though. It's one thing for a child class to override a parent class's methods to extend or alter their behavior. But, here, I've implemented an abstract method in the parent class to alter what happens when the parent class's method (speak(), in this case) is called, without overriding that parent class method itself.

View Replies View Related

Make A Java Program That Calls Object Value Initialized

Feb 23, 2014

i have this following codes and im trying to make a java program that calls an object value initialized.

public class TestClass
{
public String name;
public int age;
public void myMessage()
{
System.out.println("Hello I'm" + name + "and i'm" + age + "years old");
}
}

what i want is to put the following codes of the object.. so once i compile and run the project it executes the value of an object from the method i defined above.

TestClass myName = new TestClass();
myName.name = "Jefferson";
myName.age = 18;

my question is, it is possible to declare or define it in the same project? or i need to do this separately?

View Replies View Related

How To Trace Method Calls

Apr 1, 2015

Consider the two simple Java classes below:

class Computer {
Computer() {
System.out.println("Constructor of Computer class.");
}
void On() {
System.out.println("PC turning on...");

[Code]...

After the program run, how do I trace (1) which object call which method (2) and how many times?

View Replies View Related

Inheritance Method Calls

Jun 25, 2014

If i have 2 classes, Top and ClassB which extends Top

public class Top {
String variable;
public Top(){
setVariable();
}
void setVariable(){
variable = "variable is initialized in Main Class";

[code]....

So what is happening when ClassB inherits from Top?I know that the B constructor is calling super, so does that mean its calling setVariable (in Top?) but as its overridden in ClassB, then that is whats being called and setting the String variable?

View Replies View Related

Trying To Calculate Fine Using Method Calls

Jul 3, 2014

I am trying to calculate a fine in a PoliceOfficer object with method calls to a ParkedCar and ParkingMeter object. The word problem is:

The fine is $25 for the first hour or part of it and $20 for every additional hour of part of it.

My code is:

public class PoliceOfficer
public static final int PARKING_FINE1 = 25;
public static final int PARKING_FINE2 = 20;
public static final int NUMBER_OF_MINUTES_OVER_PARKED = 60;
public double calculateFine(){
double calculateFine = 0;

[Code] ....

obviously the fine is not calculated correctly but I'm not sure how to proceed from here...

View Replies View Related

Basic Inheritance And Static Method Calls

Jun 25, 2014

I think its a standard concept but just not getting it. I have 3 classes:

1) Base class
2) Derived class, which extends base
3) TestClass

public class Base {
public void display() {
System.out.println("Display method in Base");
}
}
class Derived extends Base {
public void display() {
System.out.println("display method in Derived");

[Code] .....

So if i run this, my results are:

Display method in Base
display method in Derived
display method in Derived

Thats cool, no problems there, but if i change my Display method in Base and Derived to static methods then the results become:

Display method in Base
display method in Derived
Display method in Base

So why oh why does obj3.display() now print "Display method in Base"?

(and yes I know the calls should be static calls, but for sake of arguments -- or is that the whole problem, that technically obj3.display() is an incorrect call as it can only be Base.display() or Derived.display() when display() is a static method ).

View Replies View Related

Using Method Calls With Returns But It Keeps On Showing Errors

Oct 12, 2014

I am trying to use method calls with returns but it keeps on showing errors. The errors say class, interface, or enum expected. I realize this error occurs if there is issue with declaring class - but i can't seem to find the error. I will post the code that shows error.
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class FuelCost extends JFrame
{
// declarations
Color black = new Color(0, 0, 0);

[Code] ....

The error states:

C:UsersPriti BhattaraiDesktopCCAC JavaFuelCost.java:290: error: ';' expected
public double calculateCostToFillTank()
^
C:UsersPriti BhattaraiDesktopCCAC JavaFuelCost.java:292: error: class, interface, or enum expected
return (averageMilesPerTank / milesPerGallonRating) * currentPricePerGallon;

[Code] ....

12 errors

Tool completed with exit code 1

View Replies View Related

Using Synchronized With Static Method Calls Used In Multiple Threads?

Jun 30, 2014

I have a multithreaded application. I have a Logger class with static methods that I use across threads. Would it behoove me to add the synchronized keyword to the static methods of the Logger class since I use this class statically in different threads?

View Replies View Related

Convert A List Of Related Object To Single Line

Jul 17, 2014

I am using Java 1.6, I have this class ....
 
import java.util.ArrayList;
import java.util.List;
public class TestDrive
{
  public TestDrive()
  {
  super();

[Code] ....
 
What is the most efficient way to group the preferences of the same type, In other word I want just a print statement to print this line.
 
BREAKFAST(Eggs,Milk),SPORTS(Basket,Tennis),....

View Replies View Related

Method That Print Data Of Single Linked List Backward Using Stack

Apr 23, 2015

I am trying out solving the question but i am stuck.The problem is to write a method that print data of single linked list backward using stack.The question is as follow

public class Stack{
public boolean isEmpty(){};
public void push(int n){};
public int peek(){};
public int pop(){};
}

public class node{
int data;
node next;
}

public class list{
node first;
}

View Replies View Related

Equals Method - Take Object Reference And Return True If Given Object Equals This Object

Mar 28, 2014

Create an equals method that takes an object reference and returns true if the given object equals this object.

Hint: You'll need 'instanceof' and cast to a (Geocache)

So far I have:

public boolean equals(Object O){
if(O instanceof Geocache){
Geocache j=(Geocache) O;
if (this.equals(j)) //I know this is wrong... but I can't figure it out
return true;
}

else return false;
}

I think I have it correct up to the casting but I don't understand what I'm suppose to do with the this.equals(). Also I'm getting an error that I'm not returning a boolean... I get this all the time in other problems. I don't get why since I have to instances of returning booleans in this. "returns true if the given object equals this object" makes no sense to me. I assume the given object, in my case, is 'O'. What is 'this' object referring to?

View Replies View Related

How To Create Object For Multiple Class Inside Single Class

Apr 22, 2015

How to create object for "class B" and call the "function_B" from other different class D where class D has no connection with class A? Here is my program.

public class A(){
void print(){}
}
class B{
void function_B(){}
}
class C{
void function_C(){}
}

Here, A, B, C are in the same package. But class D is in different package.

View Replies View Related

Which Method Is Used While Passing Or Returning A Object From The Native Method

Mar 5, 2014

Which method is used while passing or returning a java object from the native method?

View Replies View Related

Calling Object Method From Another Object

Oct 26, 2014

I've been trying to learn Java for the last 36 hours or so (after applying for a HTML/CSS job saying "Java knowledge preferred"), and decided to experiment a bit making a graphical tic-tac-toe game. I eventually managed to get that done and it's working. Working code below:

[Java] tic tac toe 1 - Pastebin

So, it works to an extent, however, the way I am capturing which cell is selected seems very sloppy, and would not work if the cells weren't squares or rectangles. So I made a copy of the project and restructured it adding the mouse event to the cells, but now I can't get JComponent to repaint. New code below:

tic tac toe 2 - Pastebin

Curiously, clicking triggers the action for all 9 cells, but I presume it's because I haven't bounded them making it think I've clicked all 9 simultaneously.

What I've tried:

Make the Cell class extend the game class and call this.repaint()- causes stack overflow.

Calling Game.GameState() within the cell clicking event and making that function static - compiler doesn't like calling repaint() inside a static function.

Making another class to make a clone of the Game object and then refresh- was never going to work....

View Replies View Related

Program To Find If Numbers Are Consecutive Or Not

Feb 23, 2014

im trying to do a program to find if numbers are consecutive or not! if they are consecutive i need a true as a return and a false when they are not... i did this program and im sure i did something wrong because i keep only true returns ..

Example: (3,5,7) (1,2,2) (7,7,9) should return a false!
Java Code: import java.util.*;
public class Consecutive{
public static void main (String [] args){
Scanner console= new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println( "The numbers (" + numbers + ") is '" + consecutive( numbers ) + "'" );
}//end of main

[code]...

View Replies View Related

Sorting Linked Lists Via Consecutive Nodes

Feb 13, 2014

I have the following code that supposed to perfrom sorting on the linked list using method sort in order usind node concept of Linked List but seems to give inlogic results. the following code tests only the values lower than the first value but i can't manage to sort the data higher than the first entered value;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import java.util.*;
public class ListNode<T extends Comparable> {
ListNode<T> nextNode;
T data;
public ListNode(T item)

[Code] .....

View Replies View Related

How To Use For Loop To Calculate Product Of Consecutive Numbers

Feb 26, 2015

I wanted to know if I was off to the right start. I am trying to write a program using the for loop the calculate the product of the consecutive numbers 4 through 8 but so for I am getting 3 values output and I only want 1 value at the print out.

The code I am using outputs the numbers too large. I am trying to see where I went wrong.

for ( int i = 4 ; i <= 8; i++)
{
int j = i++;
int k = j++;
int l = k++;
int m = l++;
System.out.println( + (i*j*k*l*m) );
}

View Replies View Related

Find If Number Entered By User Consecutive Or Not

Feb 21, 2014

I need to find if the number entered by the user are consecutive or not!

Ex:this should return a true!! This should return false!

(1,2,3) (3,5,7)
(3,2,4) (1,2,2)
(-10,-8,-9) (7,7,9)

My program seems to work ok when i enter number in order like 1,2,3 = true , and all the numbers for false seem to be working as well! my problem is when i enter number like 3,2,4 that are not in order but still are consecutive!! I thought that another if statement would be the solution but i have tray several different ones and still can't make it work !!!

Java Code:

import java.util.*;
public class Consecutive{
public static void main (String [] args){
Scanner console= new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();

[[Code] .....

View Replies View Related

Adding X Consecutive Values In Array And Getting Minimal Value

Nov 9, 2014

if I want to add a number of X consecutive values in an array and get the minimal total value along with the indexes that caused this result, how can I do that? for example:

X = 2
array[4] = (5,2,8,6,7)

start adding every 2 consecutive values as following:

array[0]+array[1] = 5+2 = 7 //minimal value
array[1]+array[2] = 2+8=10
array[2]+array[3] = 8+6= 14
array[3]+array[4] = 6+7=13

output:

minimal value = 7

indexes of minimal values are: 0 and 1

View Replies View Related

Adding Number Of X Consecutive Values In Array And Get Minimal Total Value

Nov 9, 2014

Here is my problem: if I want to add a number of X consecutive values in an array and get the minimal total value along with the indexes that caused this result, how can I do that?

For example:

X = 2
array[4] = (5,2,8,6,7)

start adding every 2 consecutive values as following:

array[0]+array[1] = 5+2 = 7 //minimal value
array[1]+array[2] = 2+8=10
array[2]+array[3] = 8+6= 14
array[3]+array[4] = 6+7=13

output:

minimal value = 7
indexes of minimal values are: 0 and 1

View Replies View Related

Creates Array Of 3 Consecutive Ints (0 - 7) User Has To Guess What Those Numbers Are

Aug 16, 2014

I have the following program. In a nutshell, I creates an array of 3 consecutive ints and the user has to guess what those numbers are, knowing that they are between 0 and 7, this is from Head First Java. In the book, the code has a bug that is made on purpose and they challenge you to fix it. As you can see bellow, every time a user's guess matches a int in the array, the NumOfHits is increased by one. When the NumOfHits is 3 (the length of the array) the game finishes.

The bug is that if you guess 1 and 1 is in the array, if you type in 1, 3 times, I will increase the NumOfHits 3 times and end the game as if you had won. To solve the bug, you need to find a way to tell the program that if the user already guessed that number, it should no longer be taken into account and we shouldn't increase the NumOfHits if the same number is provided.

I "fixed" this by searching for the index of the number that matches an int of the array, and changing that index's value to 100, since the user knows that the numbers are between 0 and 7, they will not submit 100.

The result? If the user submits 2 and 2 is in the array, the value of its indexed is replaced by 100, so that if the user submits 2 again it doesn't count as a match.

Please see the comments in the code

import java.io.*;
import java.util.Arrays;

class DotCom{
int NumOfHits = 0;
int[] LocationCells;
public void setLocationCells(int[] locs){
LocationCells = locs;

[Code] .....

The code works, but for some reason, some times I get a ArrayIndexOutOfBoundsException run time error and it appears to be somehow random. This is what I saw on the command line earlier

C:Userspablo.alvarez>java launchDotCom

Enter a number: 3
missed
Enter a number: 4
hit
Enter a number: 5
hit
Enter a number: 7
missed
Enter a number: 5
missed
Enter a number: 4
missed
Enter a number: 3
missed
Enter a number: 4
missed
Enter a number: 5
missed
Enter a number: 6

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at DotCom.checkYourSelf(launchDotCom.java:16)
at DotComGame.startGame(launchDotCom.java:59)
at launchDotCom.main(launchDotCom.java:72)

As you can see here, 3 returned 'missed' but 4 and 5 returned hit. Since the numbers are in sequence and are only 3, it makes sense that the last number is 6 (4,5,6). You will then notice that when I submitted 3 and 4 again it returned 'missed' as expected, because the numbers were already matched earlier, but then when I submitted 6, it returned the error seen above.

Sometimes this doesn't happen at all, sometimes it happens at the 2nd guess or third, it appears to be somehow random. I'm familiar with the error message, but I don't see where I'm using an index that doesn't exist in the array. The only time I'm referencing an array index is on

LocationCells[index] = 100;

but the index variable will only hold a value if the int submitted by the user matches on of the values in one of the indexes, so how is it that I'm going over the number of available indexes?

View Replies View Related

Object Method Override

Mar 7, 2014

I read the following comment at stackoverflow.com. It is not clear to me why equals in the code below does not override - i looked up Object class equals() and the signature is same.

public class Foo {
private String id;
public boolean equals(Foo f) { return id.equals(f.id);}
}

This class compiles as written, but adding the @Override tag to the equals method will cause a compilation error as it does not override the equals method on Object.

View Replies View Related

Cannot Convert From Object To E In Last Line Of Pop Method

Jul 20, 2014

I am getting this error "Type mismatch: cannot convert from Object to E" in the last line of the pop() method.

package stack;
public class Node<E> {

E item;
Node next;

Node(E item) {
this.item = item;
this.next = null;
}

[code]....

I don't understand why that error occurs despite item being declared as type E in the Node class.

View Replies View Related

Why Protected Method In Class Object

Nov 1, 2005

I don't know why class Object have two PROTECTED method -- clone() and finalize(). And in JUnit's source code, I notice that kent write :public class AClass extends Object {}I really don't understand what diffrient frompublic class AClass {}

View Replies View Related

Calling A Method On Object From Another Class?

Oct 27, 2014

I have a class for employees. This class has basic information for the employee but no real pay information. And 2 subclasses, one for employee's paid for hourly rates and one for those paid a yearly salary. Each subclass has their own pay() method, that calculates and returns their pay and extra fields relative to calculate that.

I'm just curious, if I do this and create an object for an hourly paid employee like so:

Object hourly1 = new HourlyEmployeeWilson("John Doe", "123 Tech Street",361961,"Human Resources", 0,12.50,50);

How can I utilize that classes public method of pay() to gather this instance (or hourly paid employee)'s pay? I've tried doing so via:

System.out.println(hourly1.pay());

But I get

DriverPayWilson.java:9: error: cannot find symbol
System.out.println(hourly1.pay());
^
symbol: method pay()
location: variable hourly1 of type Object
1 error

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved