Data type recognition - java

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

Related

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

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

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

charAt method is returning an integer. Need to convert to int

I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.

How do I convert a String to Double in Java using a specific locale?

I want to convert some numbers which I got as strings into Doubles, but these numbers are not in US standard locale, but in a different one. How can I do that?
Try java.text.NumberFormat. From the Javadocs:
To format a number for a different Locale, specify it in the call to getInstance.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
myNumber = nf.parse(myString);
parse() returns a Number; so to get a double, you must call myNumber.doubleValue():
double myNumber = nf.parse(myString).doubleValue();
Note that parse() will never return null, so this cannot cause a NullPointerException. Instead, parse throws a checked ParseException if it fails.
Edit: I originally said that there was another way to convert to double: cast the result to Double and use unboxing. I thought that since a general-purpose instance of NumberFormat was being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworth points out that the Javadocs for parse(String, ParsePosition) (which is called by parse(String)) say that a Long is returned if possible. Therefore, casting the result to Double is unsafe and should not be tried!
Thanks, DJClayworth!
NumberFormat is the way to go, but you should be aware of its peculiarities which crop up when your data is less than 100% correct.
I found the following usefull:
http://www.ibm.com/developerworks/java/library/j-numberformat/index.html
If your input can be trusted then you don't have to worry about it.
Just learning java and programming. Had similar question. Found something like this in my textbook:
Scanner sc = new Scanner(string);
double number = sc.nextDouble();
The book says that a scanner automatically decodes what's in a String variabel and that the Scanner class automatically adapts to the language of the set Locale, system Locale being the default, but that's easy to set to something else.
I solved my problem this way. Maybe this could work for the above issue instead of parsing?
Addition: The reason I liked this method was the fact that when using swing dialouge boxes for input and then trying to convert the string to double with parse I got a NumberFormatException. It turned out that parse exclusively uses US-number formatting while Scanner can handle all formats. Scanner made the input work flawlessly even with the comma (,) decimal separator. Since the most voted up answer uses parse I really don't see how it would solve this particular problem. You would have to input your numbers in US format and then convert them to your locale format. That's rather inconvenient when ones numeric keybord is fitted with a comma.
Now you're all free to shred me to pieces ;)
You use a NumberFormat. Here is one example, which I think looks correct.
Use NumberFormat.getNumberInstance(Locale)
This should be no problem using java.text.DecimalFormat.
Do you know which locale it is? Then you can use
DecimalFormat format = DecimalFormat.getInstance(theLocale);
format.parse(yourString);
this will even work for scientific notations, strings with percentage signs or strings with currency symbols.
Here is how you use parseDouble to convert a String to a Double:
doubleExample.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class doubleExample {
public static void main(String[] args) {
Double myDouble = new Double("0");
System.out.println("Please enter a number:");
try
{
//get the number from console
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
myDouble = Double.parseDouble(br.readLine());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
System.out.println("Double value is " + myDouble);
}
}

Categories