0

It is possible to convert a String in this way? We have same paramater and Java makes the right choise. If the value is an integer - we call parseInt(value), else if the value is an double - we call parseDouble(value) or the value is an boolean - we call parseBoolean(value);

public int parseInt(String value) {
    int newValue = Integer.valueOf(value).intValue();
    return newValue;    
}

public double parseDouble(String value) {
    double newValue = Double.valueOf(value).doubleValue();
    return newValue;
}

public boolean parseBoolean(String value) {
    boolean newValue = Boolean.valueOf(value).booleanValue();
    return newValue;
}


public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ConvertStrings convert = new ConvertStrings();   
    System.out.println("Enter the value:");
    String value = sc.next();

    //If value is an Integer - we call parseInt(value);
    //If value is an double - we call parseDouble(value);
    //If value is an boolean - we call parseBoolean(value);

    sc.close();

}
Alin
  • 1

3 Answers3

1

Scanner has really helpful methods exactly for this like hasNextInt(), hasNextLong(), hasNextBoolean(). So you can use those :).

Scanner scanner = new Scanner(System.in);

if (scanner.hasNextBoolean()) {
    boolean nextBoolean = scanner.nextBoolean();
} else if (scanner.hasNextInt()) {
    boolean nextInt = scanner.nextInt();
}
Jason
  • 4,590
  • 2
  • 9
  • 18
0

If you only have the String (i.e., "value" was obtained elsewhere), you could do this:

try {
   int ival = Integer.valueOf(value);
  ... // do something with the int
} catch (NumberFormatException ei) 
   // it isn't an integer, so try it as a double
   try {
      double dval = Double.valueOf(value);
      ... // do something with it
   } catch ( NumberFormatException ed ) {
      // Not a double, either. Assume it is boolean
      boolean b = Boolean.valueOf(value);
      ...
   }
}
FredK
  • 4,036
  • 1
  • 6
  • 11
-1

Just so you know, there is a subtle difference between the Integer.valueOf() and Integer.parseInt() methods. Although not overly important since Autoboxing was introduced in Java 1.5 it is still worth noting for specific reasons described here. After all, the Integer.valueOf() method utilizes the Integer.parseInt() method within its method code anyways. Other good reads with regards to this can be found in this SO Post and in this SO Post.

I don't know what version of Java you are coding with but the unboxing as used in:

Integer.valueOf(value).intValue();

is unnecessary.

Since you're methods are returning a primitive data type, I would use the .parseXxx..(), type methods from the Integer class instead of the valueOf() method unless of course you want to take advantage of the caching mechanism available with the valueOf() method:

 public int parseInt(String value) {
     int newValue = Integer.parseInt(value);
    return newValue;    
}

But I would take it a step further and validate the fact that the supplied string argument via the value parameter was indeed a numerical value. Even though you would normally do this before calling a method like parseInt(), I don't think it hurts to have it just in case a pre-validation wasn't done. I would use the String#matches() method along with a Regular Expression (RegEx) for this, for example:

public int parseInt(String value) {
    // Does value contain a signed or unsigned Integer 
    // type string numerical value?
    if (!value.matches("-?\\d+")) {
        //No - Throw an Exception.
        throw new IllegalArgumentException(this.getClass().getName()
                + ".parseInt() - Invalid numerical value supplied (" + value + ")!");
    }

    // Yes - Convert numerical string to a primitive int value.
    int newValue = Integer.parseInt(value);
    return newValue;
}

As time goes on you may find that using the Integer class methods directly rather than through yet another method would be easier and more beneficial. This of course would depend entirely upon what you are doing.

For your methods, you may want to try this:

public int parseInt(String value) {
    if (!value.matches("-?\\d+")) {
        throw new IllegalArgumentException(this.getClass().getName()
                + ".parseInt() - Invalid numerical value supplied (" + value + ")!");
    }
    int newValue = Integer.parseInt(value);
    return newValue;
}

public double parseDouble(String value) {
    if (!value.matches("-?\\d+(\\.\\d+)?")) {
        throw new IllegalArgumentException(this.getClass().getName()
                + ".parseDouble() - Invalid numerical value supplied (" + value + ")!");
    }
    double newValue = Double.parseDouble(value);
    return newValue;
}

public float parseFloat(String value) {
    if (!value.matches("-?\\d+(\\.\\d+)?")) {
        throw new IllegalArgumentException(this.getClass().getName()
                + ".parseFloat() - Invalid numerical value supplied (" + value + ")!");
    }
    float newValue = Float.parseFloat(value);
    return newValue;
}

public boolean parseBoolean(String value) {
    value = value.toLowerCase();
    boolean newValue = false;
    if (value.matches("true")
            || value.matches("false")
            || value.matches("yes")
            || value.matches("no")) {
        if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) {
            newValue = true;
        }
    }
    return newValue;
}

To use these methods you might do something like this:

Scanner sc = new Scanner(System.in);
//ConvertStrings convert = new ConvertStrings(); // Don't know what this class does.
String ls = System.lineSeparator();
int aINT;
double aDOUBLE;
float aFLOAT;
boolean aBOOLEAN;

String value = "";

while (!value.equals("q")) {
    System.out.print("Enter a value (q to quit): --> ");
    value = sc.nextLine();
    if (value.equalsIgnoreCase("q")) {
        break;
    }
    if (value.equals("")) {
        System.out.println(">> Invalid Entry! You must enter a String! <<" + ls);
        continue;
    }

    if (value.matches("-?\\d+")) {
        aINT = parseInt(value);
        System.out.println("A Integer (int) value of " + aINT + " was supplied." + ls);
    }
    else if (value.matches("-?\\d+(\\.\\d+)?([df])?")) {
        if (value.matches("-?\\d+(\\.\\d+)?d")) {
            aDOUBLE = parseDouble(value.toLowerCase().replace("d", ""));
            System.out.println("A Double (double) value of " + aDOUBLE + " was supplied." + ls);
        }
        else if (value.matches("-?\\d+(\\.\\d+)?f")) {
            aFLOAT = parseFloat(value.toLowerCase().replace("f", ""));
            System.out.println("A Float (float) value of " + aFLOAT + " was supplied." + ls);
        }
        else {
            aDOUBLE = parseDouble(value);
            System.out.println("A Double/Float (double/float) value of " + aDOUBLE + " was supplied." + ls);
        }
    }
    else if (value.toLowerCase().matches("true")
            || value.toLowerCase().matches("yes")
            || value.toLowerCase().matches("false")
            || value.toLowerCase().matches("no")) {
        aBOOLEAN = parseBoolean(value);
        System.out.println("A Boolean (boolean) value of '" + aBOOLEAN + "' was supplied." + ls);
    }
    else {
        System.out.println("A String was supplied! (\"" + value + "\")" + ls);
    }
}

In the above example code the following string values can be supplied:

  • A string of any size which would ultimately return and display that string if it's not a numerical value.
  • A String representation of a signed or unsigned Integer type numerical value.
  • A String representation of a signed or unsigned Double/Float type numerical value.
  • A String representation of a signed or unsigned Double type numerical value followed by the 'd' designation, for example: "453.665d" or "3236d".
  • A String representation of a signed or unsigned Float type numerical value followed by the 'f' designation, for example: "127.33f" or 32f.
  • A String representation of a Boolean type value, for example: "true" or "yes" or "false" or "no".

Regular Expressions used in code:

The parseInt() method:

if (!value.matches("-?\\d+")) {

A Integer value. If the String held within the variable value matches to be a signed or unsigned integer numerical type value containing one or more digits.


The parseDouble() and parseFloat() methods:

if (!value.matches("-?\\d+(\\.\\d+)?")) {

A Double or Float value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits.


In example run code:

else if (value.matches("-?\\d+(\\.\\d+)?([df])?")) {

A Double or Float value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits and contains the letter d OR the letter f at the end.


In example run code:

if (value.matches("-?\\d+(\\.\\d+)?d")) {

A Double value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits and contains the letter d at the end (as in: 345d or 343.42d).

In example run code:

if (value.matches("-?\\d+(\\.\\d+)?f")) {

A Float value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits and contains the letter f at the end (as in: 345f or 343.42f).

DevilsHnd
  • 6,334
  • 2
  • 14
  • 19
  • The approach of using regex is very error prone. In your example every simple number greater than Interger.MAX_VALUE (that is, every number greater than 2147483647) will get parsed falsely. Your code attempts to parse it as a integer, which is clearly wrong. Also, no warning is given in that case, despite all the fail-checking / overhead code in the examples provided. – Killgnom May 06 '21 at 11:42