I was asked to check the object returned by dimensionChange() but In Main class I am getting null pointer exception error. How can I fix this? - nullpointerexception

The method dimensionChange() in Rectangle class returning null is the given condition and it is asked to check whether the object returned by dimensionChange() is an instance of class using instanceof operator.
I can understand that the object returned by dimensionChange() is null but how can i check the returned object with instanceof operator without getting nullpointerexception error.
Any solution could be greatly helpful.
public class Main {
public static void main(String[] args) throws Exception, IOException {
//Fill your code
int l,b,n;
boolean h;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length of the rectangle");
l=sc.nextInt();
System.out.println("Enter the width of the rectangle");
b=sc.nextInt();
Rectangle r=new Rectangle(l,b);
r.display();
System.out.println("Area of the Rectangle:"+r.area());
System.out.println("Enter the new dimension");
n=sc.nextInt();
Rectangle r2=r.dimensionChange(n);
r.display();
System.out.println("Area of the Rectangle:"+r.area());
h=r2 instanceof Rectangle; **//null pointer exception**
}
}
public class Rectangle {
//Fill your code
private int length,width;
public Rectangle(int length,int width)
{
this.length=length;
this.width=width;
}
public Integer area(){
//Fill your code
return length*width;
}
public void display(){
//Fill your code
System.out.println("Rectangle Dimension");
System.out.println("Length:"+length);
System.out.println("Width:"+width);
}
Rectangle dimensionChange(Integer newDimension){
Rectangle rectangleObject = null;
//Fill your code
length=newDimension*length;
width=newDimension*width;
return rectangleObject;
}
}

Related

Why my toString JOptionPane not showing?

this code gives me an error after inserting the values of radius.
"Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.Double"
import javax.swing.*;
public class TestCircle {
public static void main(String[]args)
{
String rad1 = JOptionPane.showInputDialog("Please enter circle 1 radius: \n");
Circle circle1 = new Circle();
circle1.setRadius(Integer.parseInt(rad1));
String rad2 = JOptionPane.showInputDialog("Please enter circle 2 radius: \n");
Circle circle2 = new Circle(Integer.parseInt(rad2));
JOptionPane.showMessageDialog(null,circle1.toString());
}
public String toString()
{ return String.format("Radius:%d\nDiameter:%d\nCircumference:%.2f\nArea%.2f\n",getRadius(),circumference(),area());
}
Your methods circumference() or area() don't return a double value.
My toString method was missing diameter()...once included that it worked perfectly.
public String toString()
{
return String.format("Radius:%d\nDiameter:%d\nCircumference:%.2f\nArea%.2f\n", getRadius(),diameter(), circumference(), area());
}

Using a Prism PubSub style event in C++/CLI

I'm trying to create an event aggregator in C++/CLI, I know that the valid syntax in C# would be as follows:
//C# code
public partial class Foo : UserControl, IView, IDisposable
{
private IEventAggregator _aggregator;
public Foo(IEventAggregator aggregator)
{
InitializeComponent();
this._aggregator = aggregator;
if (this._aggregator == null)
throw new Exception("null pointer");
_subToken =_aggregator.GetEvent<fooEvent>().Subscribe(Handler, ThreadOption.UIThread, false);
}
private SubscriptionToken _subToken = null;
private void Handler(fooEventPayload args)
{
//this gets run on the event
}
}
However directly converting this to C++/CLI gives the error "a pointer-to-member is not valid for a managed class" on the indicated line. Is there a workaround? I think it has something to do with how C# generates "Action".
//C++/CLI code
ref class Foo
{
public:
Foo(IEventAggregator^ aggregator)
{
void InitializeComponent();
this->_aggregator = aggregator;
if (this->_aggregator == nullptr)
throw gcnew Exception("null pointer");
//error in the following line on Hander, a pointer-to-member is not valid for a managed class
_subToken = _aggregator->GetEvent<fooEvent^>()->Subscribe(Handler, ThreadOption::UIThread, false);
private:
IEventAggregator ^ _aggregator;
SubscriptionToken ^ _addActorPipelineToken = nullptr;
void Handler(fooEventPayload^ args)
{
//this gets run on the event
}
}
You need to explicitly instantiate the delegate object, rather than allowing C# to do this for you.
_subToken = _aggregator->GetEvent<fooEvent^>()->Subscribe(
gcnew Action<fooEventPayload^>(this, &Foo::Handler), ThreadOption::UIThread, false);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Explicitly instantiate the delegate.
// ^^^^ Object to call the delegate on.
// ^^^^^^^^^^^^^ C++-style reference to the method.

Eclipse plugin - ColumnLabelProvider display only image

So I am developing an Eclipse plug-in and using ColumnLabelProvider to provide label for the columns of my tree viewer.
However, in one of the columns, I only intend to display an image and no text. However, in the final display, Eclipse reserves blank space for the text element even if I return a null.
Is there any way to make it display only image and in the full space provided?
Here is the code snippet:
column4.setLabelProvider(new ColumnLabelProvider() {
#Override
public String getText(Object element) {
return null;
}
#Override
public Image getImage(Object element) {
/* Code to Display an image follows */
.....
}
});
ColumnLabelProvider will always leave space for the text.
You can use a class derived from OwnerDrawLabelProvider to draw the column yourself.
Something like:
public abstract class CentredImageCellLabelProvider extends OwnerDrawLabelProvider
{
protected CentredImageCellLabelProvider()
{
}
#Override
protected void measure(Event event, Object element)
{
}
#Override
protected void erase(final Event event, final Object element)
{
// Don't call super.erase() to suppress non-standard selection draw
}
#Override
protected void paint(final Event event, final Object element)
{
TableItem item = (TableItem)event.item;
Rectangle itemBounds = item.getBounds(event.index);
GC gc = event.gc;
Image image = getImage(element);
Rectangle imageBounds = image.getBounds();
int x = event.x + Math.max(0, (itemBounds.width - imageBounds.width) / 2);
int y = event.y + Math.max(0, (itemBounds.height - imageBounds.height) / 2);
gc.drawImage(image, x, y);
}
protected abstract Image getImage(Object element);
}

Method to check if number is contained in ArrayList will not work, NullPointerExcepton. Can you use ArrayList method inside a constructed method?

This is a project I am working on and it is supposed to take input from the user then which is an area code then see if it is contained in a array list. My method that I have created will not work in another class and I am not sure why, it is returning a NullPointerException.
The NullPointerException is shown at this line of code: if (mountainTime.contains(input))
This is the class with methods
package finalPro;
import java.util.ArrayList;
public class Final
{
public Final()
{
input = 0;
timezone = 0;
}
public void checkIfTrue(int y)
{
input = y;
if (mountainTime.contains(input))
{
timezone = 1;
}
else
timezone = 0;
System.out.println(timezone);
}
public int getZone()
{
return timezone;
}
public ArrayList<Integer> mountainTime;
private int input;
private int timezone;
}
Here is test class
package finalPro;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class FinalLogic
{
public static void main(String[] args)
{
ArrayList<Integer> mountainTime = new ArrayList<Integer>();
mountainTime.add(480);
mountainTime.add(602);
mountainTime.add(623); //Arizona area codes
mountainTime.add(928);
mountainTime.add(520);
mountainTime.add(303);
mountainTime.add(719); //Colorado
mountainTime.add(720);
mountainTime.add(970);
mountainTime.add(406); //Montana
mountainTime.add(505); //New Mexico
mountainTime.add(575);
mountainTime.add(385);
mountainTime.add(435); //Utah
mountainTime.add(801);
mountainTime.add(307); //Wyoming
Final myMap = new Final();
{
String x = JOptionPane.showInputDialog("Please enter a number: ");
int input = Integer.parseInt(x);
myMap.checkIfTrue(input);
}
}
}
I hope it's not too late, I haven't done anything special to fix your code, just some movement of code,
Removed the initialization logic from class FinalLogic to Final class .(btw Final name is not really good, you might be aware final is reserved word in Java. Although your name is case sensitive but still)
package finalPro;
import javax.swing.JOptionPane;
public class FinalLogic {
public static void main(String[] args) {
Final myMap = new Final();
String x = JOptionPane.showInputDialog("Please enter a number: ");
int input = Integer.parseInt(x);
myMap.checkIfTrue(input);
}
}
And here is your class Final
package finalPro;
import java.util.ArrayList;
public class Final {
public Final() {
input = 0;
timezone = 0;
// moved all initialization logic to constructor
mountainTime = new ArrayList<>();
mountainTime.add(480);
mountainTime.add(602);
mountainTime.add(623); // Arizona area codes
mountainTime.add(928);
mountainTime.add(520);
mountainTime.add(303);
mountainTime.add(719); // Colorado
mountainTime.add(720);
mountainTime.add(970);
mountainTime.add(406); // Montana
mountainTime.add(505); // New Mexico
mountainTime.add(575);
mountainTime.add(385);
mountainTime.add(435); // Utah
mountainTime.add(801);
mountainTime.add(307); // Wyoming
}
public void checkIfTrue(int y) {
input = y;
if (mountainTime.contains(input)) {
timezone = 1;
} else
timezone = 0;
System.out.println(timezone);
}
public int getZone() {
return timezone;
}
public ArrayList<Integer> mountainTime;
private int input;
private int timezone;
}
I tried in my workspace, it gives no NPE, Hope it helps.

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.