In the task, it is necessary to make a function to check the entered values for compliance with one or another type. So the question is what means can this be implemented in java? And please give an example if not difficult.
- Does it mean double or int? - nullptr
- oneis a string or unknown type entered? - Evgenii
- fourAnd how can I enter the "unknown type"? I think he enters a string and wants to make sure that it is an integer or a real one. - KoVadim pm
- as Object - Evgenii
- Yes, an array is entered and it is necessary to define an integer or real. - inham130
7 answers
Approximate outline of the solution:
String s; //введенное юзером значение try { if((s.toLowerCase().contains('e') || s.toLowerCase().contains('.')) double d=Double.parseDouble(s); //вещественный тип else long l=Long.parseLong(s); //целый тип } catch(NumberFormatException nfe) { //строчный тип } PS Did not compile and did not check, I am not a compiler :)
I understand you need to determine the type of a variable, I am not a big expert in Java, but I see two ways: 1. Java Strongly typed language, so you can save all types in an array and do an object type check with the instanceof operator:
Make your tester something like
class Typetester { void printType(byte x) { System.out.println(x + " is an byte"); } void printType(int x) { System.out.println(x + " is an int"); } void printType(float x) { System.out.println(x + " is an float"); } void printType(double x) { System.out.println(x + " is an double"); } void printType(char x) { System.out.println(x + " is an char"); } }
Then create an object and go-go ...
Typetester testMe = new Typetester(); testMe.printType( testedVariable ); - And if I do not know what type of user is going to enter, but as I understand it, in order to check, you first need to save the input data somewhere. So how to deal with it? - inham130
- 2Read data into a string and analyze it character by character (or use regular expressions for analysis) - avp
if (var instanceof Type1) { … } else if (var instanceof Type2) { … } … public static void valueOf (String str) { Format parser = NumberFormat.getInstance(); try { Object obj = parser.parseObject(str); if (obj instanceof Double) { System.out.println("double"); } else if (obj instanceof Long) { System.out.println("long"); } else { new ParseException("WTF?", 0); } } catch (ParseException pe) { throw new IllegalArgumentException("Illegal value: " + str); } } Maybe so?;-)
I would make a check with a regular value.
String inputData = "12345"; if(inputData.match("\\d")){ System.out.println("It is number"); int number = Integer.valueOf(inputData); } if(inputData.matches("\\d+\\.\\d+")){ System.out.println("It is double"); double number = Double.valueOf(inputData); } PS To drive in Integer or Double and wait for Exception, it is not very good! The program has to stop and collect Streckt, and this operation is not fast. Moreover, this is not an exceptional situation for your program. Not once met the parsing of the string in the figure with Exception from colleagues, and had to explain to them. But judging by the answers, almost everyone does it, which is very sad.
So, you have a string value, and you need to check whether it is a representation of the specified type.
For built-in types, this is not so difficult:
int :
Integer tryParseInt(String s) { try { return new Integer(s); } catch (NumberFormatException e) { return null; // не-а, не int } } double :
Double tryParseDouble(String s) { try { return new Double(s); } catch (NumberFormatException e) { return null; // не-а, не double } } String :
String tryParseString(String s) { return s; // всегда подходит } etc.
Custom types must be able to recognize themselves. If they do not know how, "recognizer" will have to write manually for each of the types.
Use this:
String s = getUserInput(); // попробовать int Integer v = tryParseInt(s); if (v != null) { // распознано, результат в v } else { // не распознано } - Only it is better not
new Integer()and notnew Double(), butInteger.valueOf()andDouble.valueOf()respectively, since in this case the value cache will be used. - falstaf - @falstaf: Not sure, the documentation says that
valueOf(String)does the same thing asnew Integer(Integer.parseInt(s)). The promise about caching is only forvalueOf(int). - VladD - uh ... only numbers in the range from -128 to 127 are cached in Integer, regardless of receipt ;-) in Double there is no caching. In Integer, this is done for a small optimization, for example, for loops. - JEcho
Solved a similar problem in JavaRush, perhaps not in the most elegant, but working way. By the input value, the print method is overloaded for different data types. Input is terminated after entering "exit"
Scanner sc = new Scanner(System.in); int val; boolean out = false; while(!out) { if (sc.hasNextInt()) { val = sc.nextInt(); if ((-32768 < val)&&(val < 32767)) print((short) val); else{ print(val); } } else if (sc.hasNextDouble()) print(sc.nextDouble()); else if (sc.hasNextLine()&&(!sc.nextLine().toLowerCase().equals("exit"))) { print(sc.nextLine()); } else { out = true; } }