Java dynamic var assigned to variable - java

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
}

Related

How can I handle incorrect user input into a scanner?

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.

unable to convert string to integer using parseInt() [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
As a beginner I know that Integer.parseInt() is used to convert strings to integers but here I tried a program but its not working
Public static void main(String args[])
{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine();
int i=Integer.parseInt(s);
System.out.println(i);
}
I want to take a line as input and convert it into integers and print but while executing it show NumberFormatException
Not all strings can be converted to integers.
For example, how should "xyz" be converted to an integer? There's simply no way. Java notifies the programmer of such situations with an NumberFormatExcpetion. And we programmers should handle such exception properly.
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
// s cannot be converted to int, do sth.
e.printStackTrace();
}
Scanner.nextInt() will throw a different exception (InputMismatchException) for invalid inputs. Nothing is changed in terms of handling inputs that simply cannot be converted to int.
Your code is correct and works fine.
Make sure that the number you are entering is within the limits of Integer [-2147483648,2147483647] as if the number is out of range then too it throws a NumberFormatException.
Although the preffered way to do this is to use sr.nextInt();
But what you have done also works just make sure that the number you are entering is actually int.
Use try and catch block .If you are giving string in place of integer , it will print "Please enter a number not string.Code is given below
Public static void main(String args[])
{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine();
try{
int i=Integer.parseInt(s);
}catch(Exception e){
System.out.println(Please enter a number not string );
}
}
You are using a line of numbers which may contain space(449 003), so
it may result in exception.
So you can remove the white spaces before parsing it to an integer.
As #luke lee mentioned alphabets and special characters can not
converted to integers, so use try catch blocks to handle those
exceptions.
try{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine().replaceAll("\\s+", "");
int i=Integer.parseInt(s);
System.out.println(i);
}catch (NumberFormatException e) {
e.printStackTrace();
}
You should use sr.nextInt(). And if you are planning on looping the entier thing, you should use sr.nextLine() right after sr.nextInt(). Otherwise the enter key you press will be taken as input resulting in unpredictable outputs.
1.Convert using Integer.parseInt()
Syntax
public static int parseInt(String s) throws NumberFormatException
The parameter s will be converted to a primitive int value. Note that the method will throw a NumberFormatException if the parameter is not a valid int.
Example
String numberAsString = "1234";
int number = Integer.parseInt(numberAsString);
System.out.println("The number is: " + number);
2.Convert using Integer.valueOf()
Example
String numberAsString = "1234";
Integer intObject = new Integer(numberAsString);
int number = intObject.intValue();
you can shorten to:
String numberAsString = "1234";
int number = new Integer(numberAsString).intValue();
or just:
int number = new Integer("1234").intValue();

How to check the input format in java

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

How do I read input that could be an int or a double? [duplicate]

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
}

Java Exception Handling - ID Number Machine

I'm in the process of improvement my skills in Java, now I am doing some exercises of exceptions, but I am stuck in this exercise:
ID Number Machine: Ask a user for a ID number. The correct input for a
id number is 10 in length and they must all be numbers.
Input: 123456790 Output: correct
Input: 12eer12345 Output: incorrect
Input: 12345678901 Output: incorrect
I don’t know what exception use to make the program work, i know the NumberFormatException can be use to check if the string is numeric, but in general im stuck, thanks is anybody can help me.
I’m trying to make it work with the great help you give me guys, in the page where the exercises are they give you the problem some code and you have to complete that code, so far I make this code with the code they give you:
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String input;
int num;
System.out.println("Enter the ID number:");
input = scanner.next();
///{Write your code here
try
{
num = Integer.parseInt(input);
}
catch(NumberFormatException nfe)
{
System.out.println("incorrect");
}
if(input.length()==10)
System.out.println("correct");
///}
}
}
I’m trying to run that and when I use the number 1234567890 the output is "correct", and if I use the string 123qwerqw the output is "incorrect" and this is correct behaviour. But when I use 1234 the program sticks and does not show anything.
The NumberFormatException is the exception that is thrown if an operation is attempted using an input value that does not match the expected form.
To see if a string is actually a number, the logic is to try to parse it to an integer.
If it throws a number format exception, it cannot be converted.
If you want to be able to deal with decimal numbers, you would need to parse to a Double using Double.ParseDouble.
Using Integer.ParseInt will fail if you enter any number that is not whole.
public boolean isValidNumber(String val) throws NumberFormatException {
try {
int i = Integer.ParseInt(val);
} catch (NumberFormatException nfe) {
//you know here that you have non numeric chars
return false;
}
//To check the length...
if (val.length > 10) {
return false;
}
return true;
}
To use the isValidNumber method....
String myNumber = "123456";
String myNotNumber = "a small town with views of the sea";
if (isValidNumber(myNumber)) {
System.out.Println(String.format("The number {0} is valid", myNumber).toString());
} else {
System.out.Println(String.format("The number {0} is not valid", myNumber).toString());
}
The logic of this is that if the number does contain any non-numeric values, the error is thrown when we try to convert the string to an int.
We catch the error, and return false from the method.
If the string does parse to an int, we know it's all numeric (and as we're using an integer, we know it's not a decimal).
The second test deals with the length - again, we return a false if the value does not match the criteria specified. Anything longer than 10 chars is invalid, so return a false.
The final return statement can only be reached if all the preceding checks have passed.
I'm not certain this will compile straight off (I'm writing it from memory having not used Java for about 2 years), but that is the basic logic for it.
Here is the code working for my problem:
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String input;
int num;
System.out.println("Enter the ID number:");
input = scanner.next();
///{Write your code here
try
{
num = Integer.parseInt(input);
System.out.println(input.length()==10?"correct":"incorrect");
}
catch(NumberFormatException nfe)
{
System.out.println("incorrect");
}
///}
}
}

Categories