Count digits after decimal including last zero - java

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

Related

How to implement a recursive method for converting an integer to binary representation

I am writing a method to recursively convert an integer value to its binary representation.
The code that I wrote below accomplishes the task by just using a method, but I'd like to know how to actually write out a full method.
import java.util.Scanner;
public class Exercise18_21 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
System.out.print("Enter a character: ");
System.out.printf("%d decimal is binary %s",decimal,dec2Bin(decimal));
}
//input: integer
//output: binary representation of integer as a string
public static String dec2Bin(int decimal){
return Integer.toBinaryString(decimal);
}
}
My question is how can this be accomplished with recursion?
I want to preserve your code as mush as I can. Therefore I just add a new method successiveDivision(int)
import java.util.Scanner;
public class Exercise18_21 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
System.out.print("Enter a character: ");
System.out.printf("%d decimal is binary %s", decimal, dec2Bin(decimal));
}
// input: integer
// output: binary representation of integer as a string
public static String dec2Bin(int decimal) {
return successiveDivision(decimal);
}
public static String successiveDivision(int dec) {
if (dec <= 0) {
return "";
} else {
int bit = dec % 2;
return successiveDivision(dec / 2) + bit;
}
}
}
You can implement it the same way you can do it with pen and paper. Use the modulo operation.
divided by 2 is your parameter for the recursive call and mod 2 is your current digit.

Java InputMismatchException Error

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....");

Simple Java way to input decimal and round to nearest integer

I am using the Java SDK to compile. Need I say, I am a beginner.
Here is the code I tried to use to "Ask user to input decimal and code should output an integer. (round to nearest integer)
import java.util.*;
public class readDecimal {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println(“Please enter a decimal number:“);
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
“ rounded to the nearest integer is “ + intNumber);
}
}
What am I doing wrong? I saw the other posts however they seem much to complicated for a beginner. Can you please help?
Thank you,
Diane
Your quotation marks are incorrect; they are unicode for some reason. Replace all the quotations by manual typing them in, in you System.out.println statements.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println("Please enter a decimal number:");
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
" rounded to the nearest integer is " + intNumber);
}
You can round double numbers using Math.round method.
import java.util.*;
public class RoundingDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double num1;
double num2;
System.out.print("Please enter a decimal number: ");
num1 = sc.nextDouble();
num2 = Math.round(num1);
System.out.println(" Rounded to the nearest integer is " + num2);
}
}

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
}

Categories