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+")
Related
Hi I'm still new to java and I would like to know how to check if the user only input numbers and not letters my problem comes in when I had to parse the input from string to double to be able to add decimals together in the console. But when I googled to see how to check if my input is only numbers I had to take in a string input that gives me *2 inputs(hope I'm making sense).Is there maybe a easier version to do this or am I missing something.
public class javaCalculator {
public static void main(String[] args){
//initializing two scanners for numbers and operations and creating 3 variables
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
//getting user input for the type of operations and numbers they want to enter
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
//My program didn't want to take decimals, so I had to parseDouble which takes the input as a string and then
//converts(parse) it to a double which then makes my program run with decimal numbers
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
String num2 = numbers.nextLine();
number2 = Double.parseDouble(numbers.nextLine());
boolean check1 = num1.matches("[0-9]+");
boolean check2 = num2.matches("[0-9]+");
if (check1 == true && check2 == true){
System.out.println("...");
}else {
System.out.println("Only enter numbers not letters.");
}
//Using if else statements to check what operation was chosen above and then depending on
//that choice(+, -, *, /) printing a suitable answer to console
//Creating a calculation variable to use in the writing to a file
String calculation;
if (operator.equals("+")){
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
System.out.println(calculation);
}else if (operator.equals("-")){
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
System.out.println(calculation);
}else if (operator.equals("*")){
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
System.out.println(calculation);
}else if (operator.equals("/")){
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
System.out.println(calculation);
}else{
calculation = operator + ":" + " Is not a valid operator!";
System.out.println(calculation);
}
Your code is trying to read the same number twice:
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
What you should do is read the number as a string, confirm that it is a number and then parse it only if it matches.
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
boolean check1 = num1.matches("[0-9]+");
if(check1){
number1 = Double.parseDouble(num1);
}
else{
//Error handling
}
Alternatively you can simply try to parse the string directly and catch the exception i.e.
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
try{
number1 = Double.parseDouble(num1);
} catch(NumberFormatException e){
//Error handling
}
Your approach is OK. Although Scanner lib provides the nextDouble() method I recommend using the regular expression control you are using. Even though there are some little things to fix:
You are parsing (convert from String to double) first, and then checking format. If for example, the user enters a letter your program will fail when parseDouble tries to convert the String to double. So, read the String from the input, apply the match control, and if there is no Error then parse.
Your regular expression is matching any String that has 1 or more numbers. For example, the input Hello1 will match because there is at least one number. Then the parse will fail because Hello1 is not a valid number. You have to use a regular expression that matches only numbers. This expression will look like this: "^[0-9]+$"
The ^ character means that the expression must match at the beginning of the line, and the $ character force that the expression match at the end of the line. In other words, this expression should have numbers from the beginning to the end of the string. It would be a good thing to add a .trim() (num1.trim().matches("[0-9]+");) to delete any extra white space at the beginning or at the end.
The third recommendation is that if you don't want to use decimals may be Double type is not the proper data type to use. Double can represent decimals. The proper type should be Integers.
number1 = Integer.parseInt(num1);
#christopher When you raise error you are printing a message but the program keeps running. That's why you get the Error commented on #Turamarth solution comment
I'm prompting a user for a number and am trying to determine the amount of even, odd, and zeros in that number
/* This program will determine and print the number of even, zero, and odd digits in
* an integer
*
* Author: Marco Monreal
* Date: 11/01/2016
*/
import java.util.Scanner;
public class PP5_3
{
public static void main(String[] args)
{
String exit_loop, go_again, user_num, first_char_string;
int odds, evens, zeros;
int first_char; //, second_char, third_char, fourth_char, fifth_char, sixth_char, seventh_char, eighth_char, ninth_char, tenth_char;
Scanner scan = new Scanner (System.in);
evens = 0;
odds = 0;
zeros = 0;
exit_loop = "no"; //initializing while loop
while (exit_loop.equals ("no"))
{
System.out.println ("Choose any number between 0 and 2,147,483,647. Don't include commas please.");
user_num = scan.next ();
I'm getting stuck around this area; "first_char" is not returning the digit value that I want/need.
//assigning a variable to each character of user_num
first_char = user_num.lastIndexOf(0);
/*second_char = user_num.charAt(1);
third_char = user_num.charAt(2);
fourth_char = user_num.charAt(3);
fifth_char = user_num.charAt(4);
sixth_char = user_num.charAt(5);
seventh_char = user_num.charAt(6);
eighth_char = user_num.charAt(7);
ninth_char = user_num.charAt(8);
tenth_char = user_num.charAt(9);*/
//copy every character into a string value
first_char_string = String.valueOf(first_char);
if (first_char == 2 || first_char == 4 || first_char == 6 || first_char == 8)
{
evens++;
}
else if (first_char_string.equals("1") || first_char_string.equals("3") || first_char_string.equals("5") || first_char_string.equals("7") ||
first_char_string.equals("9"))
{
odds++;
}
else
zeros++;
} //ends while loop
System.out.println ("There are " +evens+ " even numbers, " +odds+ " odd numbers, and " +zeros+ "zeros in ");
scan.close ();
} //ends main method
} //ends class
Hi take a look on this line:
user_num = scan.next (); // this will scan your user input, but does not jump to the next line
you might want to use:
user_num = scan.nextLine();
Also you made a mistake in your lastIndexOf(char) method.
This method expects a char. you supply this method an int e.g:
first_char = user_num.lastIndexOf(0);
this works because java interprets your number a an ASCI-number. the char representated by ASCI "0" is null. What you want to do is search for the character '0'. Like the following:
first_char = user_num.lastIndexOf('0');
The same for your equalisations:
first_char == 2 ---> first_char == '2';
Another notice. Please use camel case istead of underscores. instead of user_num you should write userNum. Thats the standard.
Yet another notice. The lastIndexOf() method will return the nummber of the last occurence of the parameter. e.g:
String test = "hello test";
test.lastIndexOf(e); // this will return 7 for it is the number ofthe last occurence of 'e'
I think yu want to use charAt(0) this returns the charactere at specified position
Last Notice. why are you comparing char values representing numbers ?
why not do the following:
int userNum = Integer.valueOf(yourCharHere).
Update
If I understood your comment correctly the your 'X' in the snippet below is defined by the user
first_char = userNum.charAt(X);
If I get you right you have a problem because you dont know how long the input of the user is. Instead of assigning the individual numers to variables I would do the following:
//Parsing your String into a int
int userNum = Integer.valueOf(yourUserInputHere);
Arraylist singleDigits = new ArrayList()<>;
//This goes through all digits of your number starting with the last digits
while (userNum > 0) {
singleDigits.add( userNum % 10);
userNum = userNum / 10;
}
//Reverses your list of digits
Collections.reverse(singleDigits);
Example input: 13467
your List should look like: [1],[3],[4],[6],[7]
This enables you to get the single digits by calling:
singleDigits.get(0) -> [1];
singleDigits.get(3) -> [6];
...
I hope that helps
First create sets that are containing odd/even/zero numbers:
Set<Integer> odds = "13579".chars().boxed().collect(Collectors.toSet());
Set<Integer> evens = "02468".chars().boxed().collect(Collectors.toSet());
Set<Integer> zero = "0".chars().boxed().collect(Collectors.toSet());
Then get an input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Choose a number:");
String number = scan.next();
scan.close();
Parse number character by character to find out how many digits are matching each set:
long numberOfOdds = number.chars().filter(odds::contains).count();
long numberOfEvens = number.chars().filter(evens::contains).count();
long numberOfZeros = number.chars().filter(zero::contains).count();
Finally, display the result:
System.out.println("There are " + numberOfEvens + " even numbers, " + numberOfOdds + " odd numbers, and " + numberOfZeros + " zeros in ");
In my program, a user inputs a float number with TEMP (for example TEMP 10.05).
The program should take only the float part and convert it into fareheit. And finally printing out the result in float.
How could I do that?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("The following program takes a float value with the word 'TEMP'in celcius, and converts into farenheit");
System.out.println("Enter the temperature with TEMP: ");
while (true) {
String input = s.next();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren=celcius+32.8;
// float=result
System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");
}
}
}
The program shows this error:
The problem with your code is that you use
String input = s.next();
this only returns TEMP. You need to use
String input = s.nextLine();
this should return the full string.
And unrelated to you question, you are also converting the temperatures wrong. It should be
float tempFaren = celcius*1.8f + 32.0f;
You could use Float.parseFloat(yourString);
Example:
String x = "TEMP 10.5";
float y = Float.parseFloat(x.substring(5,x.length()));
System.out.println(y);
You can use indexOf to find the first space, substring to get the test of the string after the position of the space, and parseFloat to parse the number from string into a float:
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
The same thing broken down to steps:
int spacePos = input.indexOf(' ');
String celsiusStr = input.substring(spacePos + 1);
float celsius = Float.parseFloat(celsiusStr);
UPDATE
Your modified code doesn't compile either (you have typing error in "celcius", and other problems).
This compiles, and correctly parses the floating point part:
String input = "TEMP 10.5";
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren = celsius + 32.8f;
System.out.println("Temperature in farehheit is : " + tempFaren + " F.");
Finally,
another way to extract the float value at the end of the string is to strip non-numeric values from the beginning, for example:
float celsius = Float.parseFloat(input.replaceAll("^\\D+", ""));
Disclaimer: none of the examples I gave above will work for all possible inputs, they are tailored to the example inputs you gave. They can be made more robust if necessary.
Try something like this
while (true) {
String input = s.nextLine();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
try{
double faren=Double.parseDouble(input.substring(input.lastIndexOf(' ')+1))+32.8;
//float tempIntoFarenheit= input+32.8
System.out.println("Temperature in farenheit: "+faren);
}catch(Exception e){
System.out.println("Something was wrong with the temperature, make sure the input has something like 'TEMP 50.0' ");
System.out.println(e.toString());
}
} else {
System.out.println("Wrong input. Try again: ");
}
}
You can use the following method:
static float extractFloatWithDefault(String s, float def) {
Pattern p = Pattern.compile("\\d+(\\.\\d+)?");
Matcher m = p.matcher(s);
if ( !m.find() ) return def;
return Float.parseFloat(m.group());
}
Like this:
while (true) {
String input = s.next();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
float celsius = extractFloatWithDefault(input, -999);
if ( celsius > -999 ) {
float tempFaren=celcius+32.8;
System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");
}
else System.out.println("Please include a number");
}
}
This method would extract the first number it finds in the strings and uses it or return the default value if there is no valid floating number or integer.
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...)
is there a way to find if the value parsed and returned by java.io.StreamTokenizer.nval (e.g. 200) was an integer or a floating number ?
Thanks
Edited:
I want to be able to know if the input was '200' or '200.0'.
I don't think it is possible with StringTokenizer, it's too old. You can use Scanner to do the job:
Scanner fi = new Scanner("string 200 200.0");
fi.useLocale(Locale.US);
while (fi.hasNext()) {
if (fi.hasNextInt()) {
System.out.println("Integer: " + fi.nextInt());
} else if (fi.hasNextDouble()) {
System.out.println("Double: " + fi.nextDouble());
} else {
System.out.println("String: " + fi.next());
}
}
Documentation for the class is here
As you are essentially trying to figure out if a double is an int or not, you can create a BigDecimal and test its scale() method. You could also use the Math static method floor() and test the return value against the original.
if(Math.floor(myStreamTokenizer.nval) == myStreamTokenizer.navl)) {
//treat it as an int
} else {
//treat it as a double
}
Of the two, I would use the Math.floor option, as it would be more efficient.
I would use the modulus operator:
if (yourNval % 1 > 0)
{
// nval is floating point.
}
else
{
// nval is an integer.
}
This works because modulus works with floating point numbers in Java as well as integers.
UPDATE: Since you specify a need to distinguish integers from doubles with zero-value decimal portions, I think you'll have to do something like the following:
Double(yourNval).toString().indexOf('.');
So a more-complete function will look like:
if (yourNval % 1 > 0)
{
// nval is floating point.
}
else
{
// nval is an integer.
// Find number of trailing zeroes.
String doubleStr = Double(yourNval).toString();
int decimalLoc = doubleStr.indexOf('.');
int numTrailingZeroes = 0;
if (decimalLoc > 0)
{
numTrailingZeroes = doubleStr.length() - decimalLoc - 1;
}
}