Java double Input Validation - java

below is the code:
Scanner scan = new Scanner(System.in);
String input = scan.next();
try{
double isNum = Double.parseDouble(input);
if(isNum == Math.floor(isNum)) {
System.out.println("Input is Integer");
//enter a double again
}else {
System.out.println("Input is Double");
//break
}
} catch(Exception e) {
if(input.toCharArray().length == 1) {
System.out.println("Input is Character");
//enter a double again
}else {
System.out.println("Input is String");
//enter a double again
}
}
taken from here: how to check the data type validity of user's input (Java Scanner class)
however, when i input 1.0 or 0.0, it is still considered as an integer, is 1.0 not considered a double?
Please help guys, thank you!

If you want to treat 1.0 as a Double an 1 as an Integer, you need to work with the input variable, which is of type String.
Java will always treat Double x = 1 in the same way as Double y = 1.0 (meaning 1 is a valid Double), so you will not be able to distinguish them with code.
Since you have the original string representation of the input, use a regex or some other validation to check it. For instance a sample regex pattern for double would look like "[0-9]+(\.){0,1}[0-9]*" and for an integer "[0-9]+" or "\d+"
Here is an example:
final static String DOUBLE_PATTERN = "[0-9]+(\.){0,1}[0-9]*";
final static String INTEGER_PATTERN = "\d+";
Scanner scan = new Scanner(System.in);
String input = scan.next();
if (Pattern.matches(INTEGER_PATTERN, input)) {
System.out.println("Input is Integer");
//enter a double again
} else if (Pattern.matches(DOUBLE_PATTERN, input)) {
System.out.println("Input is Double");
//break
} else {
System.out.println("Input is not a number");
if (input.length == 1) {
System.out.println("Input is a Character");
//enter a double again
} else {
System.out.println("Input is a String");
//enter a double again
}
}

1.0 is typically considered a valid double, but the code has been written explicitly to threat whole numbers as invalid doubles(printing that they are intergers). To change this behavior remove the inner if:
try{
double isNum = Double.parseDouble(input);
System.out.println("Input is Double");
} catch(Exception e) {
if(input.toCharArray().length == 1) {
System.out.println("Input is Character");
}else {
System.out.println("Input is String");
}
}

Check, if the string you are validating contains a dot - then, if parseDouble succeeds, it could be treated as a double value (even for 1.0).

You check if 1.0 is equal to 1, which mathematically is correct. Therefore your first if will return true, and it will be considered an int. It seems that the whole idea with the program is to check doubles and see if they have decimals or not.

Math.floor(x)
returns a double, and since 1.0 is indeed the same as 1.0, your program will enter the first if-block.

I think your test is flawed. You say "0.0 and 1.0 are parsed as integers" based on the condition
isNum == Math.floor(isNum)
Double-precision floating-point numbers are not a random garbage of bits: they express a precise quantity, and it happens that the numbers zero and one can be represented exactly (see the bit patterns) and thus they are equal to Math.floor(val) (btw, this happens for lots of integer values, not only zero and one)
So you should reconsider your test before your code. Consider that likely a user will never input an integer or a double: what she types is a decimal number, and you should deal with the input depending on what it's used for (the choice is among String, BigDecimal, Number, Integer, Double and so on...)

Related

How to loop wrong data type inputs? [duplicate]

This question already has an answer here:
While loop to determine if entered value is a double
(1 answer)
Closed 1 year ago.
I know there are lots of questions similar to this but I can't understand most of it, also I can't see any similar questions related to java language.
So can you guys help me how to loop this question if the input is not a double data type?
The code:
System.out.println("Enter first number");
num1 = input.nextDouble();
System.out.println("Enter second number");
num2 = input.nextDouble();
I really appreciate anyone who tries to answer, tia!!
This is a solution (without exception handling). It loops until two Doubles have been entered. So it is possible to enter this:
3
4.2
or also:
www
3
abc
4.2
Both will give the same result
3
4.2
Note that the code is locale sensitive in regard of the numbers you enter at the command prompt (meaning that the decimal sign depends on your computer settings – in Germany for example it is the comma and not the dot, so you would enter 4,2):
Scanner scanner = new Scanner(System.in);
Double part1 = null;
Double part2 = null;
while (true) {
if (scanner.hasNextDouble()) {
if (part1 == null ) {
part1 = scanner.nextDouble();
} else {
part2 = scanner.nextDouble();
break;
}
} else {
scanner.next(); // The input is not a Double, so just drop it
}
}
scanner.close();
System.out.println(part1);
System.out.println(part2);
If you add the line scanner.useLocale(Locale.ROOT) after creating the scanner:
Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.ROOT);
the decimal sign will be the dot '.' like in 4.2 independent of the settings of your computer.
I like to create a separate method to validate input. If the value is invalid, then I have the method return -1. Then I'll have a while loop that checks if the input is -1, if so, than it'll ask the for a new input value till it's correct. There are many ways to go about it. But the gist is something like this.
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
double num1 = validateDouble(input);
while (num1 == -1) {
num1 = validateDouble(input);
}
System.out.println(num1);
}
private static double validateDouble(Scanner scanner) {
String input = scanner.nextLine();
try {
double i = Double.parseDouble(input);;
return i;
}catch (InputMismatchException | NumberFormatException e) {
if (input.equals("q")) {
System.exit(0);
}
System.out.println("Please try again.");
return -1;
}
}

How to write a program to get three inputs from a user: a string (convert to numbers), an int and a double and add their values

I need to write a program that requests and accepts three inputs from a user- a string, an int and a double.
The program should pass the inputs to a method that converts the string to its equivalent numeric value and adds this value to the sum of the remaining inputs. The program should display the result to the user.
The letter a is worth 1, b worth 2, all the way up to the letter z being worth 26.
If it contains a digit, the value of that character is the value of the digit itself, 0 is worth 0, 1 worth 1, all the way up to 9 worth 9.
Any other character in the string (for example: !$?*&^%) is worth 0.
What I have so far is in my code below
import java.util.Scanner;
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter a string");
String input1 = myObj.nextLine();
if (!input1.matches("[a-zA-Z_]+!$?*&^%")) {
System.out.println("Invalid String");
}
else {
System.out.println("Please enter a integer");
}
int input2 = myObj.nextInt();
System.out.println("Please enter a double");
double input3 = myObj.nextDouble();
}
}
Sample output
Please enter a string: dad6!
Please enter an integer: 10
Please enter a decimal number: 2.5
Result is: 27.5
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
float charSum=0;
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter a string");
String input1 = myObj.nextLine();
char[] arr=input1.toCharArray();
for(int i=0;i<arr.length;i++){
int ascii=(int)arr[i];
if(ascii>=97&&ascii<=122){
charSum=charSum+ascii-96; //for a-z
}
else if(ascii>=65&&ascii<=90){
charSum=charSum+ascii-64; //for A-Z
}
else if(ascii>=48&&ascii<=57){
charSum=charSum+ascii-48; //ascii for number
}else{
charSum=charSum+0; //ascii for special Character
}
}
System.out.println("Please enter a Integer");
int integerValue = myObj.nextInt();
charSum+=integerValue;
System.out.println("Please enter a Double");
Double doubleValue = myObj.nextDouble();
charSum+=doubleValue;
System.out.println(charSum);
}
}
here,I have taken string and find out the ascii value of each and subtracted 96 because the ascii value of a-> 97 .A->65 (so if a needs to be 1 it must be 97-96=1) and for special characters as you asked it to be 0 so added that to the sum variable.Since the double is also and input so the output can be either float or double .I have taken float.Hope this solution solves your query
https://www.onlinegdb.com/online_java_compiler can check the code on this compiler online.

Write a Java program that reads in two floating-point numbers and tests whether they are the same up to three decimal places

Why my flow is going to else part of the if statement
public class Exercise6MatchDecimalValues {
public static void main(String[] args) throws Exception
{
Scanner stream = new Scanner(System.in);
System.out.println("Input floating point number: ");
Double input1= stream.nextDouble();
System.out.println("Input another floating point number: ");
Double input2 = stream.nextDouble();
String input1StringDecimal = String.valueOf(input1).split("\\.")[1].substring(0, 3); //To get the first 3 decimal values
String input2StringDecimal= String.valueOf(input2).split("\\.")[1].substring(0, 3); //To get the first 3 decimal values
String input1StringWhole=String.valueOf(input1).split("\\.")[0]; //To get the whole value
String input2StringWhole=String.valueOf(input2).split("\\.")[0]; // //To get the whole value
System.out.println("input1StringWhole"+input1StringWhole);
System.out.println("input1StringDecimal"+input1StringDecimal);
System.out.println("input2StringWhole"+input2StringWhole);
System.out.println("input2StringDecimal"+input2StringDecimal);
if(input1StringDecimal == input2StringDecimal && input1StringWhole==input2StringWhole) {
System.out.println("They are same");
}else
{
System.out.println("They are different! ");
}
}
}
Input floating point number: 123.1234
Input another floating point number: 123.1234
input1StringWhole 123
input1StringDecimal 123
input2StringWhole 123
input2StringDecimal 123
They are different!
Float 23232.231231 is rounded to 23232.23.
So if you convert that float to a string and take the portion after the decimal point, it is only two characters long, and substring(0,3) raises an exception.
Use double then it should work. You are giving double value to float hence it gets round off.

Why Does The JVM Return This Integer?

I have made quite a simple number rounding application, since I am quite a beginner, there may be some errors, some debugging to do and we could go on and on however that is not why I am here. Whenever I type in an integer that is larger than the capacity of the value "int", it either returns "-1" or an incredibly large small number (it's negative so further away from zero) such as "-572589576". I want to why and how the JVM returns this. The code for my program is listed below:
import java.util.Scanner;
public class NumberRounder {
private static Scanner userInput2;
public static void main(String[] args) {
System.out.println("--- Number Rounder ---");
Scanner userInput = new Scanner(System.in);
System.out.println("The number you enter will round it to the nearest value.");
System.out.print("Enter any decimal number: ");
if (userInput.hasNextDouble()) {
System.out.println("\nCalculating...");
System.out.println("Number Rounding...");
double chosenNumber = userInput.nextDouble();
int roundedNumber = (int) Math.round(chosenNumber);
if (roundedNumber == -1) {
System.out.println("\nAn ERROR occured.");
System.out.println("That number is too large for our servers. Sorry for the inconvenience.");
System.exit(0);
}
System.out.println(chosenNumber + " has been rounded to " + roundedNumber);
} else if (!(userInput.hasNextDouble())) {
System.out.println("\nThat is an illegal response...");
userInput2 = new Scanner(System.in);
System.out.println("\nThe number you enter will round it to the nearest value.");
System.out.print("Enter any decimal number between 1-10: ");
double chosenNumber = userInput2.nextDouble();
int roundedNumber = (int) Math.round(chosenNumber);
System.out.println(chosenNumber + " has been rounded to " + roundedNumber);
} else {
System.out.println("Something wrong happened...");
}
}
}
I have solved the problem of when it returns "-1" however I still don't know how to completely solve this problem. That is why I am here asking the question:
Why does the JVM return such as random number?
Whenever I type in an integer that is larger than the capacity of the value "int"
What did you expect to get from it? Exception?
it will not be there. Java just circle from MAX_VALUE to MIN_VALUE
Just try:
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
And look what it prints.
PS. that is about how number sign represented in actual binary format of int value.
You're forcing a double (64-bits) into an int, so the resulting value is truncated and you see these "random" (although they're not random) values. You should use a long to provide additional space for your numbers.

find decimal in a given number

How can i find decimal(dot) in a given number in java.
I am getting input from user, he may give integer or float value.
I need to find he entered integer or float, is it possible?
if yes could u tell me please.
--
Thanks
Assuming you got the digits of the number in a String, it would be
String number = ...;
if (number.indexOf('.') > -1)
...
you can try with yourNumberString.indexOf("."). If it returns a number greater than -1 there's a dot in the input.
Anticipating your need, I would suggest that you use java.util.Scanner for number parsing, and use its hasNextXXX methods instead of dealing with parseInt etc and deal with NumberFormatException.
import java.util.*;
String[] inputs = {
"1",
"100000000000000",
"123.45",
"blah",
" "
};
for (String input : inputs) {
Scanner sc = new Scanner(input);
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("(int) " + i);
} else if (sc.hasNextLong()) {
long ll = sc.nextLong();
System.out.println("(long) " + ll);
} else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("(double) " + d);
} else if (sc.hasNext()) {
System.out.println("(string) " + sc.next());
}
}
This prints:
(int) 1
(long) 100000000000000
(double) 123.45
(string) blah
You do not need to explicitly search for the location of the decimal point as some answers suggest. Simply parse the String into a double and then check whether that double represents an integer value. This has the advantage of coping with scientific notation for doubles; e.g. "1E-10", as well as failing to parse badly formatted input; e.g. "12.34.56" (whereas searching for a '.' character would not detect this).
String s = ...
Double d = new Double(s);
int i = d.intValue();
if (i != d) {
System.err.println("User entered a real number.");
} else {
System.err.println("User entered an integer.");
}
Some other ways to do this:
given
String input = ...
the following evaluates to true if it's a decimal number
input.split(".").length == 2
or
input.matches(".+\\..+")
or
!input.matches("\\d+")

Categories