How to handle exception using JOptionPane class [duplicate] - java

This question already has answers here:
Scanner Exception Retry
(2 answers)
Closed 3 years ago.
So, I need help with this code. This code will make the user input a double value like double radius. and calculate the area and perimeter of the circle. But I need to check if the radius is correct or not like, if the radius is negative or not and if the user enters a char or a string with it. so if the user enters 34.5gd the code should output "Invalid entry, please try again" and use a loop to input the value again.
I can get the negative part and using JOptionPane I am to get a dialogue box saying "Invalid entry, please try again", but I am unable to check the input for a char or string.
This code is for the driver class
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class CircleValidationApp1
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
String line;
Scanner input = new Scanner (System.in);
System.out.println("Enter the radius");
Circle obj = new Circle();
NegativeDoubleException obj1 = new NegativeDoubleException();
line = input.next();
obj1.Checkradius(line);
if(obj1.Checkradius(line)==true)
{
System.out.println("valid input");
}
else
{
JOptionPane.showMessageDialog(frame, "Error, Please try again");
line = input.next();
}
input.close();
}
}
This class should handle the input and throw the exception.
import javax.swing.JFrame;
public class NegativeDoubleException
{
Double radius;
String line;
Boolean flag = radius instanceof Double;
Circle obj = new Circle();
JFrame frame = new JFrame();
public void getvalue(String r){
r=this.line;
}
public void setvalue(String r){
getvalue(r);
}
public Boolean Checkradius(String r){
Boolean flag = false;
try
{
radius = Double.parseDouble(line);
flag = true;
}catch( NumberFormatException e)
{
flag = false;
}
return flag;
}
}

it is very easy you will surround the code that wants from the user to enter a number
with try...catch statement
like this
try{
//the code that wants from the user to enter the radius
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Invalid entry, please try again");
}
and when any Exception happens it will give the invalid entry message and you can close the message and write a new raduis without crashing the program

first problem : you must make variable line double not String and in the setters and getters methods of radius you make the setter double and it must be void
and the getter must be double and in the getter you will writereturn radius
and you will do the following changes
public class Circle2 {
double radius;
double area ;
double perimeter;
public void setradius(double r)
{
this.radius=r;
}
public double getradius(){
return radius;
}
public void perimeter()
{
System.out.println(2*3.14*radius);
}
public void area(){
area = Math.PI*radius*radius;
System.out.println(area);
}
}
note : I use the pi method in the math class to get more accurate resultsMath.PI
second : I make some changes on your main class
public class mainc {
public static void main(String[] args) throws IOException {
double l;
Circle2 obj = new Circle2();
Scanner s;
s = new Scanner(System.in);
l = s.nextDouble();
obj.setradius(l);
obj.perimeter();
obj.area();
to make anexception if someone didnot enter a number you will surround all the code in the main by try and catch
you will do that
public class mainc {
public static void main(String[] args) throws IOException {
double l;
Circle2 obj = new Circle2();
Scanner s;
try{
s = new Scanner(System.in);
l = s.nextDouble();
obj.setradius(l);
obj.perimeter();
obj.area();
}catch(Exception e){
System.out.println(e);
System.out.println("enter a number");
s = new Scanner(System.in);
l = s.nextDouble();
}
}
}
we added the s = new Scanner(System.in); and the l = s.nextDouble(); again because if an exception happened it will continue doing there work and dont close

Related

What there is no resource leak when Scanner variable declared in class data field?

When I do write this:
import java.util.*;
public class Test {
// static Scanner input = new Scanner(System.in);
static double y;
public static void main(String[] args) {
double x = someMethod(5);
}
private static double someMethod(int nr) {
Scanner input = new Scanner(System.in);
try {
y = input.nextDouble();
} catch (InputMismatchException e) {System.out.println("Type in a double");}
return y + nr;
}
}
I get "resource leak" error message.
But when I do write this:
import java.util.*;
public class Test {
static Scanner input = new Scanner(System.in);
static double y;
public static void main(String[] args) {
double x = someMethod(5);
}
private static double someMethod(int nr) {
try {
y = input.nextDouble();
} catch (InputMismatchException e) {System.out.println("Type in a double");}
return y + nr;
}
}
It just does work. Why is there no resource leak when I define input Scanner on the class data field?
What is the difference between declaring a variable on the data field vs in a method?
When you have Scanner input = new Scanner(System.in); in the method, you're creating a new Scanner instance every time the method is called, and you only use it once. This creates garbage because now you will have a new Scanner which isn't being used anymore every time you use the method.
If you instantiate the Scanner in the class instead, you create it once and re-use it, preventing your program from having garbage.

Passing another instance of the same class and comparing it's stored values to current stored values

Last objective of my assignment asks to create a method matches(). It receives another GenericMemoryCell as a parameter, and returns true if both of its stored values can be found in the stored values of the current GenericMemoryCell. Order of stored values is not important.
Creating the method was not difficult, but I am lost on how to call it from main() because I cannot wrap my head around the concept of passing another instance of GenericMemoryCell. Where am I getting another pair of storedValueA and storedValueB in the first place? Is matches() "running" a virtual instance of the entire program within itself?
import java.util.*;
public class GenericMemoryCell<T>{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter valueA: ");
String readerA = input.next();
System.out.print("Enter valueB: ");
String readerB = input.next();
GenericMemoryCell<String> values = new GenericMemoryCell<>(readerA, readerB);
System.out.println("storedValueA: " + values.readA());
System.out.println("storedValueB: " + values.readB());
values.writeA(readerA);
values.writeB(readerB);
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
public void writeA(T x)
{ storedValueA = x; }
public void writeB(T y)
{ storedValueB = y; }
public boolean matches(GenericMemoryCell<T> that){
return (this.storedValueA.equals(that.storedValueA) && this.storedValueB.equals(that.storedValueB)); }
private T storedValueA, storedValueB;
}
I think you need something like this
public class GenericMemoryCell {
public static void main(String[] args) {
GenericMemoryCell g1 = new GenericMemoryCell();
//set g1 values here
GenericMemoryCell g2 = new GenericMemoryCell();
//set g2 values here
System.out.println(g1.matches(g2));
}
public boolean matches(GenericMemoryCell g) {
//implement the logic here
return ...;
}
}
Hopefully, it might work for you. However, if you want system to ask for inputs repeatedly, you need to some kind of loop.
public class GenericMemoryCell {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstInput = scanner.nextInt();
System.out.println("Please enter second input");
int secondInput = scanner.nextInt();
list.add(firstInput);
list.add(secondInput);
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstArg = scannerObj.nextInt();
System.out.println("Please enter second input: ");
int secondArg = scannerObj.nextInt();
boolean isMatches = isInputMatches(firstArg, secondArg, list);
if (isMatches) {
System.out.println("These inputs were already stored before. Please try again with different inputs");
} else {
System.out.println("The inputs are successfully stored. Thank you.");
}
scanner.close();
scannerObj.close();
}
private static boolean isInputMatches(int firstArg, int secondArg, List<Integer> list) {
return list.contains(firstArg) && list.contains(secondArg);
}
}

Java Basic Object Oriented Gratuity Calculator

I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.

infinite while loop; input validation; don't know what to do to make it read an if before input is placed what should I do?

I'm pretty new at programming so sorry for bad explanations and/or badly written code...
Anyways, i'm currently working on an assignment using "method overload" and I want to be able to get a double or an int from the user.
My first code worked, so I decided to add an else to the end of the last if statement that checked for bad input and reiterated the entire code. The problem is that while the code works fine when you put numbers the first time, if you put in bad input it will start the while loop and keep re-iterating the code block regardless of any input. I know that it is just ignoring the if statements because their is no previous input of any sort(or anything stopping it?). I need some way of the code checking getting the input and then checking whether it is an integer or double before declaring the variable type...Or if there is some better method please share... if you need any more knowledge reply to this post or whatever...here
Also, its not finished, call it a draft if you
public class LoanRates {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean x = false;
while(x = true){
System.out.println("please enter a number");
x = false;
if (in.hasNextInt()){
int rate = 0;
rate = getNumbers(rate, in);
System.out.println(rate);
break;
} else if( in.hasNextDouble()){
double rate = 0;
System.out.println("please enter a number");
rate = getNumbers(rate, in);
System.out.println(rate);
break;
}else {
System.out.print("please enter a number");}
}
System.out.print("did it work?");
}
public static double getNumbers(double rate, Scanner in){
rate =in.nextDouble();
return rate;
}
public static int getNumbers(int rate, Scanner in){
rate = in.nextInt();
return rate;
}
}
You are using while(x = true) then it is always true
first you must initialize x variable to true. Otherwise it will not go inside the while loop
boolean x = true;
try while(x == true) and make sure to change the value of variable x to false when it is necessary
Try like this. But it is better to pass the double or int value rather than passing the scanner reference to the getNumbers methods
package test;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LoanRates {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Please enter a number");
String input = in.next();
try {
int rate = Integer.parseInt(input);
// you can use the rate variable and change your method to accept the input value
System.out.println(getNumbers(rate));
break;
} catch (NumberFormatException e) {
try {
double rate = Double.parseDouble(input);
// you can use the rate variable and change your method to accept the input value
System.out.println(getNumbers(rate));
break;
} catch (NumberFormatException ex) {
System.out.println("Invalid number.");
}
}
}
System.out.print("did it work?");
}
public static double getNumbers(double rate) {
// rate calculation logic
return rate;
}
public static int getNumbers(int rate) {
// rate calculation logic
return rate;
}
}

Making a GUI program from Commandline

import java.util.Scanner;
I am trying to turn this into a GUI program, and what I kind of came up with gives me a lot of errors, so if anyone could help me figure that out, that would be great.
public class Problemtwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the side: ");
double side = input.nextDouble();
double area = 3 * 1.73205 * side * side / 2;
System.out.println("The area " + area);
}
}
This is the GUI I tried to create
import java.swing.JOptionPane;
import java.lang.Math;
public class GUI_Problemtwo {
public static void main(String[] args) {
double side;
double area;
StringsideString = JOptionPane.showInputDialog("Enter the side: ");
return;
}
// Convert string to double
double side = Double.parseDouble(sideString);
double side = input.nextDouble();
// Compute the area
double area = 3 * 1.73205 * side * side / 2;
// Display results
String output = "The area is " + area;
}
I just know that I'm really doing something wrong. Also I have another GUI that I'm able to input into a dialog box, but I can't get it to pull up any output in a dialog box, it just looks like it doesn't even stop running...
import javax.swing.JOptionPane;
import java.io.*;
public class GUI_Account {
public static void main(String[] args)throws IOException {
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
double bal=0;
int month,i;
// Prompts user to enter a number of months
String MString = JOptionPane.showInputDialog("Enter number of months: ");
if (MString == null) {System.out.println("User prompt cancelled");
return;
}
month=Integer.parseInt(kb.readLine());
for(i=0;i<month;i++) {
bal=(bal+100)*1.00417;
}
// Convert string to double
double M =Double.parseDouble(MString);
// Display results in dialog box
String output = "The amount is " + bal; JOptionPane.showMessageDialog(null, output);
}
}

Categories