Java InputMismatchException Error - java

I've been given a task to make some conversions from ft and in to cm. I've gotten most of this down and the conversions do work. I also want to include the statement of A negative number... or A non-digit... when I type a string, for example, or a negative number, to display said message.
The problem I am getting is that when I do type up a string or negative number, I get the output of testProgram.NegativeNumberException when I enter -9, for example. And testProgram.NonDigitNumberException, when I enter joe, for example.
I am thinking there is something wrong in the catch but not sure exactly where it won't click.
package testProgram;
import java.util.InputMismatchException;
import java.util.Scanner;
public class conversion{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double cm = -1;
while(cm == -1){
cm = convertToCentimeters(scan);
if(cm!=-1){
System.out.println("Your result = " +cm);
}
else{
System.out.println("Please enter the values again.");
}
scan.nextLine();
}
}
public static double convertToCentimeters(Scanner scan){
double centimeters = -1;
try{
double foot = getFootValue(scan);
double inch = getInchValue(scan);
double totalInches = foot * 12 + inch;
centimeters = totalInches * 2.54;
}catch(NegativeNumberException e1){
System.out.println(e1);
}
catch(NonDigitNumberException e2){
System.out.println(e2);
}
return centimeters;
}
public static double getFootValue(Scanner scan) throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the foot value: ");
double foot = scan.nextDouble();
if(foot <= 0){
throw new NegativeNumberException ("A negative foot value has been entered.");
}
return foot;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit foot value has been entered.");
}
}
public static double getInchValue(Scanner scan)throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the inch value: ");
double inch = scan.nextDouble();
if(inch <= 0){
throw new NegativeNumberException ("A negative inch value has been entered.");
}
return inch;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit inch value has been entered.");
}
}
}

Alternatively to #Scary's suggestion, you can add a constructor to your custom exceptions as -
NegativeNumberException(String str) {
System.out.println(str);
}
This shall help you print the message when you
throw new NegativeNumberException ("A n....");

Related

Count digits after decimal including last zero

I have this,
import java.util.Scanner;
public class StringDecimalPartLength {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
Double string_Temp = Double.parseDouble(input.nextLine().replace(',', '.'));
String string_temp = Double.toString(string_Temp);
String[] result = string_temp.split("\\.");
System.out.print(result[1].length() + " decimal place(s)");
}
}
it works until I enter a number with trailing zero, such as 4,90. It ignores the zero and returns 1.
How to fix this? Thank you!
Since you are already reading the input as a string, you can save that value and then test to see if it is a valid decimal number:
import java.util.Scanner;
public class StringDecimalPartLength {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
String value = input.nextLine().replace(',', '.');
try {
Double.parseDouble(value);
String[] result = value.split("\\.");
System.out.print(result[1].length() + " decimal place(s)");
} catch (NumberFormatException e) {
System.out.println("The entered value is not a decimal number.");
}
}
}
4.9 or 4.90 as a double are both represented by the same approximation. There is no difference between them.
You can, of course, do what you want using String processing on the input. However, you may find BigDecimal a better data type for what you are doing. It distinguishes between 4.9 and 4.90, and can represent each of them exactly.
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
System.out.println(new BigDecimal(4.9));
System.out.println(new BigDecimal(4.90));
BigDecimal x1 = new BigDecimal("4.9");
System.out.println(x1);
System.out.println(x1.scale());
BigDecimal x2 = new BigDecimal("4.90");
System.out.println(x2);
System.out.println(x2.scale());
}
}
Output:
4.9000000000000003552713678800500929355621337890625
4.9000000000000003552713678800500929355621337890625
4.9
1
4.90
2
Omari, I adjusted your code like this and it worked, thanks!
if(result[0].length() == 0 ){
System.out.print("The entered value is not a decimal number.");
}
else {
System.out.print(result[1].length() + " decimal place(s)");
}
} catch (NumberFormatException e) {
System.out.println("The entered value is not a decimal number.");
}catch (ArrayIndexOutOfBoundsException e) {
System.out.print("Error Message" );
}

How do I effectively clear a buffer in Java?

This is a method for the main class of this problem.
I have an issue when the user inputs a non-numeric value for the requested information.
Example)
Enter a distance in meters: jam
Incorrect value. Please select a distance in meters greater than zero.
Enter a distance in meters: Incorrect value. Please select a distance greater than zero.
Enter a distance in meters:
This is the output that occurs when this method is called. How do i correct this?
public static double validDistance (String prompt,
double minValue) {
Scanner keyboard = new Scanner (System.in);
double value;
String errorMessage = "Incorrect value. Please select a distance in "
+ "meters greater than zero\n";
// Protects distance input from incorrect value
// (non-numeric or too low)
do {
System.out.print(prompt);
if (keyboard.hasNextDouble()) {
value = keyboard.nextDouble();
if (value <= minValue) {
System.out.println(errorMessage);
} else {
break; // Exit loop
}
} else {
System.out.println(errorMessage);
keyboard.nextLine(); // Clears buffer
}
} while (true);
return value;
}
I realize this doesn't directly answer your question.
I personally find that dealing with the Scanner buffer is incredibly annoying, so I prefer just reading line by line and doing the processing myself. For example:
public static double validDistance(String prompt, double minValue)
{
Scanner keyboard = new Scanner(System.in);
String errorMessage = "Incorrect value. Please select a distance in meters greater than zero\n";
while (true) {
System.out.print(prompt);
String line = keyboard.nextLine();
try {
double result = Double.parseDouble(line);
if (result >= minValue) {
keyboard.close(); // You should always close a Scanner when you're done!
return result;
}
} catch (NumberFormatException e) {
}
System.out.println(errorMessage);
}
}

How to fix user input error when a non number is entered in .nextDouble?

So I am taking Java as part of math degree requirements and have stumbled on a problem with this code. Essentially the code is supposed to take in numbers from the user until they type a zero. It works fine as long as only numbers are entered. However if the user enters a letter or symbol the program gets an exception. Is there a simple way I can validate user input as a number without getting an exception?
import java.util.Scanner;
public class SamsAdder
{
public static void main(String[] args)
{
double userInput = 1;
double sum = 0;
Scanner in = new Scanner (System.in);
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
}
System.out.println("The sum of the numbers is " + sum + ".");
}
}
So I've tried the try/catch as you showed it. I'm still getting an exception with non numbers though. Entered the code as follows:
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
try{
userInput = in.nextDouble();
}
catch(NumberFormatException nfe){
System.out.println("Invalid Number");
}
sum = sum + userInput;
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class SamsAdder {
public static void main(String[] args) {
double userInput = 1;
double sum = 0;
Scanner in = new Scanner(System.in);
while (userInput != 0) {
try {
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
} catch (InputMismatchException nfe) {
System.out.println("Invalid Number");
in.next();
}
}
in.close();
System.out.println("The sum of the numbers is " + sum + ".");
}
}

Code for only accepting integers

import javax.swing.*;
import java.awt.*;
public class JCD {
public static void main(String[] args) {
String input, inputs;
int input1, input2;
input = JOptionPane.showInputDialog("Enter first number");
inputs = JOptionPane.showInputDialog("Enter second number");
input1 = Integer.parseInt(input);
input2 = Integer.parseInt(inputs);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}// close void
private static int findGCD(int number1, int number2) {
// base case
if (number2 == 0) {
return number1;
}// end if
return findGCD(number2, number1 % number2);
}// end static
} // close class
What can I add so that it will only accept integers? If not given an integer then it will go back to ask again.....
Put your input request in a while statement, check if it's an int, if not repeat the loop, otherwise exit. Do it for both your inputs.
Something like this
public static void main(String[] args) {
String input=null, inputs=null;
int input1 = 0, input2=0;
boolean err=true;
do{
try{
input = JOptionPane.showInputDialog("Enter first number");
input1 = Integer.parseInt(input);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
err=true;
do{
try{
inputs = JOptionPane.showInputDialog("Enter second number");
input2 = Integer.parseInt(inputs);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}
Note that this solution requires you to initialize your variables when you declare them
String input = null, inputs = null;
int input1=0, input2=0;
You should try with "try and catch".
input = JOptionPane.showInputDialog("Enter first number");
inputs=JOptionPane.showInputDialog("Enter second number");
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
// establish and use the variables if the characters inserted are numbers
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, e+ "is not a number");
//display a warning to le the user know
}
You could use something like this :-
boolean inputAccepted = false;
while(!inputAccepted) {
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
inputAccepted = true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog("Please input a number only");
}
... do stuff with good input value
}

Converting decimal to binary using Java JOptionPane

In the coding I have done, I have a problem at the very end. When the program actually converts the decimal into binary form, the JOptionPane window separates each number in the binary answer. I don't know how to fix this.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class decimalToBinary {
Scanner console = new Scanner (System.in);
public static void main(String [] args){
String digit;
String wrong = ("Enter a value greater than 0");
String binary_answer;
double entered_value;
digit = JOptionPane.showInputDialog
("Enter the decimal number: ");
entered_value = Double.parseDouble(digit);
if (entered_value < 0)
JOptionPane.showMessageDialog(null, wrong, "ERROR",
JOptionPane.ERROR_MESSAGE);
else
{
binary_answer = (binaryform((int) entered_value) + ".");
JOptionPane.showMessageDialog(null, binary_answer, "Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
private static Object binaryform(int number) {
double remainder;
if (number <=1) {
JOptionPane.showMessageDialog(null, number , "Result",
JOptionPane.INFORMATION_MESSAGE);
return null;
}
remainder= number %2;
binaryform( number >> 1);
JOptionPane.showMessageDialog(null, remainder , "Result",
JOptionPane.INFORMATION_MESSAGE);
{
return " ";
}
}
}
Looking at your code, I've noticed that you're calling the binaryform() multiple times.
You should stack the result in an array or collection before showing it in a joptionpane.
make it something like this
//introduce a field variable
String remainderStr='';
private static Object binaryform(int number) {
double remainder;
//if (number <=1) {
// JOptionPane.showMessageDialog(null, number , "Result",
// JOptionPane.INFORMATION_MESSAGE);
// return null;
//}
remainder= number %2;
//append on string, to display after the conversion is done.
remainderStr =remainderStr + remainder;
binaryform( number >> 1);
//move this part to main
//JOptionPane.showMessageDialog(null, remainder , "Result",
// JOptionPane.INFORMATION_MESSAGE);
//{
// return " ";
//}
}
}

Categories