Why my toString JOptionPane not showing? - sql

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());
}

Related

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?

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;
}
}

JOptionPane cannot find symbol in module

So, the assignment for this week was all about modularization, and the code must contain 6 modules, which is why it looks like a complete mess. Anyway, I'm getting an error that says the module cannot find JOptionPane even though I declared it for the main method. I've posed the code below. Any help appreciated.
Specifically, I'm getting it right here, with this line of code posted at the top.
{ public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionpPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
}
//This program will find the area or volume of a circle or sphere,
respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the
program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the
module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or
'N' to Quit");
}
showGoodbye ();
}
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a
shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionpPane.showInputDialog("Please enter 'C' for a
Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusofItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the
radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusofItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, string itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
system.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius, itemShape);
}
/////////////////////////////////////////////// seperating method
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius *
itemRadius);
system.out.print("The volume of the sphere in cubic inches is "
+sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
}
Anyway, I'm getting an error that says the module cannot find
JOptionPane even though I declared it for the main method
You have a typo in this line
typeOfShape = JOptionpPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
It should be JOptionPane instead of JOptionpPane. Remove the p

javafx and serializability

In the old AWT libraries, the Point class and the Color class were serializable. Neither is in JavaFX. I would like to save an array list of Drawables to a file; here is the interface
import javafx.scene.canvas.GraphicsContext;
public interface Drawable
{
public void draw(GraphicsContext g);
}
When I attempt to to this, I get bombarded by NotSerializableExceptons.
What is the best alternate course of action? All of my drawables know their color and size.
Use a custom serializable form and serialize the data you need. E.g.
import javafx.scene.canvas.GraphicsContext ;
import javafx.scene.paint.Color ;
import javafx.geometry.Rectangle2D;
import java.io.Serializable ;
import java.io.ObjectInputStream ;
import java.io.ObjectOutputStream ;
import java.io.IOException ;
public class DrawableRect implements Drawable, Serializable {
private transient Color color ;
private transient Rectangle2D bounds ;
public DrawableRect(Color color, Rectangle2D bounds) {
this.color = color ;
this.bounds = bounds ;
}
#Override
public void draw(GraphicsContext g) {
g.setFill(color);
g.fillRect(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight());
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// write color:
s.writeDouble(color.getRed());
s.writeDouble(color.getGreen());
s.writeDouble(color.getBlue());
s.writeDouble(color.getOpacity());
// write bounds:
s.writeDouble(bounds.getMinX());
s.writeDouble(bounds.getMinY());
s.writeDouble(bounds.getWidth());
s.writeDouble(bounds.getHeight());
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
double r = s.readDouble();
double g = s.readDouble();
double b = s.readDouble();
double opacity = s.readDouble();
color = new Color(r,g,b,opacity);
double x = s.readDouble();
double y = s.readDouble();
double w = s.readDouble();
double h = s.readDouble();
bounds = new Rectangle2D(x,y,w,h);
}
}
If you have fields that are serializable (or primitive types), you don't mark them transient, and the defaultReadObject and defaultWriteObject will handle them. If you have fields that are not serializable, mark them transient and serialize the data in a form that can be serialized as in the example.
Obviously, since you have multiple implementations of this interface which may all need this functionality, it might benefit you to create a helper class with some static methods:
public class DrawableIO {
public static void writeColor(Color color, ObjectOutputStream s) throws IOException {
s.writeDouble(color.getRed());
s.writeDouble(color.getGreen());
s.writeDouble(color.getBlue());
s.writeDouble(color.getOpacity());
}
public static Color readColor(ObectInputStream s) throws IOException {
double r = s.readDouble();
double g = s.readDouble();
double b = s.readDouble();
double opacity = s.readDouble();
return new Color(r,g,b,opacity);
}
public static void writeBounds(Rectangle2D bounds, ObjectOutputStream s) throws IOException {
s.writeDouble(bounds.getMinX());
s.writeDouble(bounds.getMinY());
s.writeDouble(bounds.getWidth());
s.writeDouble(bounds.getHeight());
}
public static Rectangle2D readBounds(ObjectInputStream s) throws IOException {
double x = s.readDouble();
double y = s.readDouble();
double w = s.readDouble();
double h = s.readDouble();
return new Rectangle2D(x,y,w,h);
}
}
and then of course the methods in your Drawable implementations reduce to something like
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
DrawableIO.writeColor(color, s);
DrawableIO.writeBounds(bounds, s);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
color = DrawableIO.readColor(s);
bounds = DrawableIO.readBounds(s);
}

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.

How to display a number without % sign in Java's JProgressBar?

When I use JProgressBar, I want it to display a number from 0 to 32, not a percent, so before it starts, it will show 0, after I click start button, it will show 1 , 2 , 3 ... 32
How to do it ?
One way to do it is by overriding the getString() method of JProgressBar:
public class CustomProgressBar extends javax.swing.JProgressBar {
#Override
public String getString() {
return getValue() + "";
}
}
Assuming you set the min and max values to 0 and 32 respectively, and the progress values using the setValue() method, your progress bar will now show integers from 0 to 32.
And here is a working example:
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
public class ProgressBarExample {
public static void main(String[] args) {
final CustomProgressBar customProgressBar = new CustomProgressBar();
customProgressBar.setMaximum(32);
customProgressBar.setStringPainted(true);
new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
int value = 0;
Thread.sleep(1500);
while (value < customProgressBar.getMaximum()) {
Thread.sleep(250);
value ++;
customProgressBar.setValue(value);
}
return null;
}
}.execute();
JOptionPane.showMessageDialog(null, customProgressBar, "Progress bar example", JOptionPane.PLAIN_MESSAGE);
}
}