i need to check whether the number input is in decimal format or in floating point format in java coding.
in simple terms how would this check be possible?
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextDouble())
//double stuff here
else if (scanner.hasNextFloat())
//Float stuff here
Here is a small method I quickly whipped up that you may find interesting....
public static boolean isFloatingPoint(Object number) {
String type = number.getClass().getSimpleName().toUpperCase();
return type.equals("FLOAT") || type.equals("DOUBLE");
}
You can use the same concept to determine any Object passed to your method, perhaps even:
public static boolean isJButton(Object component) {
String type = component.getClass().getSimpleName().toUpperCase();
return type.equals("JBUTTON");
}
Related
I am creating a class to use which handles user input. This is so that in other projects I can call methods from the class without having to worry about creating scanners in every new project.
There will be a separate method within the class to handle different variable types (float, int, String etc..). I have started with the float type:
import java.util.Scanner;
public class Input {
public static float floatInput() {
Scanner in1 = new Scanner(System.in);
float in;
if (in1.hasNextFloat()) {
in = in1.nextFloat();
return in;
} else {
System.out.print("Incorrect input type, try again");
floatInput();
return 0;
}
}
This method works just fine, except that it must return a float in the else part. In this instance it is a zero, so when inputting to a calculator (for example), the zero causes any output to equal zero.
Is there a way of returning an 'empty' float value to overcome this problem?
Does anybody have any better suggestions for handling incorrect scanner input in general?
Thank you.
You can just read your input as a String and check if it is a float value, else loop until it is or the user gets tired:
public static float floatInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a float:");
for(;;){
try{
return Float.parseFloat(scanner.next());
} catch(NumberFormatException e){
System.out.println("Incorrect input type, try again:");
}
}
}
There is no such thing as an 'empty' float. A float that has not been initialized defaults to 0.0f. If you were to return your 'in' variable, instead of just returning 0 in your else statement it would return 0.0.
Click here to learn more about default values for primitive data types in Java.
public static float floatInput() {
Scanner in1 = new Scanner(System.in);
float in = in1.nextFloat();
while (/*in.isGood()*/) {
System.out.println("Incorrect input type, try again:");
in = in1.nextFloat();
}
return in;
}
This will prevent to call recursivelly while you still haveing instances of the method running on the background with open Scanners waiting for the return.
Also, you can be sure that the output will have nextFloat.
But you need to find a better way of checking if the float is correct such as a try catch block with a parse inside. hasNextFloat() won't tell you.
I want to create a Java program where
a user will input something and the output will show what type of data the input is..?
For example:
Input: 25
Output: integer
Input: ABC
Output: string
Input: 12.7
Output: float/double.
Please help as I am clueless on how to work this out
This should work for your purpose:
import java.util.Scanner;
public class DataType
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
if(in.hasNextByte(2))
System.out.println("Byte");
else if(in.hasNextInt())
System.out.println("Integer");
else if(in.hasNextFloat())
System.out.println("Float");
else if(in.hasNextBoolean())
System.out.println("Boolean");
else if(in.hasNext())
System.out.println("String");
}
}
Note that the order of if...else statements is very important here because of the following set relations with respect to patterns:
All byte patterns can be integers
All integer patterns can be floats
All float patterns can be Strings
All booleans can be Strings
There are quite a lot of hasNext..() methods in the Scanner class, such as BigInteger, short, and so on. You may refer the Scanner class documentation for further details.
A simple approach could go like this; starting with some input string X.
If X can be parsed as Integer --> it is an int/Integer
Then you try Long
Then Float
Then Double
If nothing worked, you probably have a string there
( with "parsing" I mean using methods such as Integer.parseInt() ... you pass in X; and when that method doesn't throw an exception on you, you know that X is an Integer/int )
But: such a detection very much depends on your definition of valid inputs; and potential mappings. As there zillions of ways of interpreting a string. It might not be a number; but given a correct format string ... it could be timestamp.
So the very first step: clarify your requirements! Understand the potential input formats you have to support; then think about their "mapping"; and a potential check to identify that type.
You can get a string and try to parse it as other types:
Scanner s = new Scanner(System.in);//allows user input
input = s.nextLine();//reads user input
try{//java will try to execute the code but will go to the catch block if there's an exception.
int inputInt = Integer.parseInt(input);//try to convert input to int
catch(Exception e){
e.printStackTrace();//this tell you exactly what went wrong. If you get here, then the input isn't an integer.
}
//same with double
I have a chicken and egg issue of sorts. I'm use to dynamic typing (python) so please be gentle on me if this is a basic thing.
I have a scanner, but I want to allow the user to enter either a string or an integer (1 or 'option1'). Because it's a user input, I don't know the resulting type (int or string). I need to get the user input from the scanner, assign it to a variable, and then pass that variable to an overloaded method.
The problem is that I need to declare the variable type. But, it can be either. How do I handle this?
EDIT
To clarify, I was thinking of doing something like this (Below is pseudo code):
public static float methodname(int choice){
//some logic here
}
public static float methodname(String choice){
//some logic here
}
Scanner input = new Scanner( System.in );
choice = input.nextLine();
System.out.println(methodname(choice));
The problem that i'm having is the declaration of 'choice'. What do i put for the type?
You can take it as a String and try to convert it to an int. If the conversion happens without problems you can use the int version, otherwise use the String version.
String stringValue = ...
try {
// try to convert stringValue to an int
int intValue = Integer.parseInt(stringValue);
// If conversion is possible you can call your method with the int
call(intValue);
} catch (NumberFormatException e) {
// If conversion can't happen call using the string
call(stringValue);
}
Take the input value as String, convert it to integer using
String number = "1";
int result = Integer.parseInt(number);
if it parses then you can continue using it as a number. And if it fails it will throw NumberFormatException. So you can catch the exception and proceed it with string.
try{
String number = "option1";
int result = Integer.parseInt(number);
// proceed with int logic
} catch(NumberFormatException e){
// handle error and proceed with string logic
}
This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 7 years ago.
I'm writing a program in which I need to take input from the keyboard. I need to take a number in, yet I'm not sure if it's an int or a double. Here's the code that I have (for that specific part):
import java.io.*;
import java.util.*;
//...
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
I know I can get a String and do parseInt() or parseDouble(), but I don't know which one it'll be.
Well, ints are also doubles so if you assume that everything is a double you will be OK with your logic. Like this:
import java.io.*;
import java.util.*;
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
It only get complex if you needed the input to be an integer for whatever reason. And then, parseInt() to test for int would be just fine.
Just use a double no matter what it is. There is no noticeable loss on using a double for integral values.
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
Then, if you need to know whether you've gotten a double or not, you can check it using Math.floor:
if (choice == Math.floor(choice)) {
int choiceInt = (int) choice);
// treat it as an int
}
Don't mess with catching NumberFormatException, don't search the string for a period (which might not even be correct, for example if the input is 1e-3 it's a double (0.001) but doesn't have a period. Just parse it as a double and move on.
Also, don't forget that both nextInt() and nextDouble() do not capture the newline, so you need to capture it with a nextLine() after using them.
What I would do is get String input, and parse it as either a double or an integer.
String str = input.next();
int i = 0;
double d = 0d;
boolean isInt = false, isDouble = false;
try {
// If the below method call doesn't throw an exception, we know that it's a valid integer
i = Integer.parseInt(str);
isInt = true
}catch(NumberFormatException e){
try {
// It wasn't in the right format for an integer, so let's try parsing it as a double
d = Double.parseDouble(str);
isDouble = true;
}catch(NumberFormatException e){
// An error was thrown when parsing it as a double, so it's neither an int or double
System.out.println(str + " is neither an int or a double");
}
}
// isInt and isDouble now store whether or not the input was an int or a double
// Both will be false if it wasn't a valid int or double
This way, you can ensure that you don't lose integer precision by just parsing a double (doubles have a different range of possible values than integers), and you can handle the cases where neither a valid integer or double was entered.
If an exception is thrown by the code inside the try block, the code in the catch block is executed. In our case, if an exception is thrown by the parseInt() method, we execute the code in the catch block, where the second try-block is. If an exception os thrown by the parseDouble() method, then we execute the code inside the second catch-block, which prints an error message.
You could try using the floor function to check if it is a double. In case you don't know, the floor function basically cuts off any decimal numbers. So you can compare the number with and without the decimal. If they are the same, then the number can be treated as an integer, otherwise a double (assuming you don't need to worry about large numbers like longs).
String choice = input.nextLine();
if (Double.parseDouble(choice) == Math.floor(Double.parseDouble(choice)) {
//choice is an int
} else {
//choice is a double
}
I am trying to create a text based calculator. I have a main class and a calc class. The calc class is where everything will happen, and it will be called in the main class. My problem is several variables in my calc class. It is easier to see in code.
import java.util.Scanner;
public class Calc {
String op;
public void operation(String opt){
System.out.println("What operation would you like to perform?");
Scanner operation = new Scanner(System.in);
op = opt;
String op = operation.toString();
getOp(op);
}
public String getOp(String op){
return op;
}
And later on in my code.
public void calculate(){
operation(op);
getNums(1,2);
if(op == "Division"+"division"+"/"){
double value = 1/2;
System.out.println("Your answer is"+value);
}
if(op == "Multiplication"+"multiplication"+"*"){
double value = 1*2;
System.out.println("Your answer is"+value);
}
if(op == "Addition"+"addition"+"+"){
double value = 1+2;
System.out.println("Your answer is"+value);
}
if(op == "Subtraction"+"subtraction"+"-"){
double value = 1/2;
System.out.println("Your answer is"+value);
}
}
My problem is that I can't seem to set the value of op with the scanner, and I don't know if the value of my numbers (1 and 2) have been set either. Any help is greatly appreciated, thank you.
FWIW, I would use .nextInt instead of .toString. This would ensure it took in a number and then pass it into your store for conditional to take place.
Plus, I think you would be better off using a switch statement on the calculations, in which case you could leave it as .toString or change it to .next and pass in the char or string.
I think like βнɛƨн Ǥʋяʋиɢ's suggestion, you should not call the operation() in your Cal class. if it just prompts user and takes input, it should be in main class.
As i don't see the error message so i guess one of the problem you can get is you declare your op variable one and initiate another local variable op in your operate() function to catch the user's input.
Another thing is shouldn't your Scanner object call the method nextLine() instead of toString() to catch the user's input. I don't have my comp with me so can't post any code but maybe you can try to modify your code first and post some error message to be clearer.