杰瑞科技汇

Java字符串如何转Short类型?

Of course! Converting a String to a short in Java is a common task. The primary and safest way to do this is by using the Short.parseShort() method.

Java字符串如何转Short类型?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the best methods, potential errors, and advanced techniques.

The Main Method: Short.parseShort()

This is the standard method for converting a String that represents a decimal number into a primitive short.

Syntax

public static short parseShort(String s) throws NumberFormatException

How it Works

It takes a String as input and attempts to parse it. If the string contains a valid integer value that can fit into a short, it returns that value as a short. If the string is not a valid number, it throws a NumberFormatException.

Example

public class StringToShortExample {
    public static void main(String[] args) {
        String strNumber = "12345";
        String strNegative = "-987";
        try {
            // Convert the string to a short
            short number1 = Short.parseShort(strNumber);
            short number2 = Short.parseShort(strNegative);
            System.out.println("The string '" + strNumber + "' converts to the short: " + number1);
            System.out.println("The string '" + strNegative + "' converts to the short: " + number2);
            // You can now use the short in calculations
            short result = (short) (number1 + 100);
            System.out.println("Result of " + number1 + " + 100 is: " + result);
        } catch (NumberFormatException e) {
            System.err.println("Invalid number format. Please check the string.");
            e.printStackTrace();
        }
    }
}

Output:

Java字符串如何转Short类型?-图2
(图片来源网络,侵删)
The string '12345' converts to the short: 12345
The string '-987' converts to the short: -987
Result of 12345 + 100 is: 12445

Handling Different Number Radices (Bases)

The parseShort method can also parse numbers in different bases (like binary, octal, or hexadecimal) using an overloaded version that accepts a radix.

Syntax

public static short parseShort(String s, int radix) throws NumberFormatException
  • s: The string to parse.
  • radix: The radix (base) to use for parsing. For example, 2 for binary, 8 for octal, 10 for decimal, and 16 for hexadecimal.

Example

public class StringToShortRadixExample {
    public static void main(String[] args) {
        String binaryStr = "101010";      // Represents 42 in decimal
        String octalStr = "52";           // Represents 42 in decimal
        String hexStr = "2A";             // Represents 42 in decimal
        try {
            short fromBinary = Short.parseShort(binaryStr, 2);
            short fromOctal = Short.parseShort(octalStr, 8);
            short fromHex = Short.parseShort(hexStr, 16);
            System.out.println("Binary '" + binaryStr + "' (base 2) is: " + fromBinary);
            System.out.println("Octal '" + octalStr + "' (base 8) is: " + fromOctal);
            System.out.println("Hex '" + hexStr + "' (base 16) is: " + fromHex);
        } catch (NumberFormatException e) {
            System.err.println("Invalid number format for the given radix.");
            e.printStackTrace();
        }
    }
}

Output:

Binary '101010' (base 2) is: 42
Octal '52' (base 8) is: 42
Hex '2A' (base 16) is: 42

Error Handling: NumberFormatException

This is the most common error you'll encounter. It happens when the String cannot be converted to a short.

Common Causes for NumberFormatException:

  1. Non-numeric characters: "12a34"
  2. Empty string:
  3. String with only whitespace:
  4. Number out of range: The number is too large or too small to fit in a 16-bit signed integer (-32,768 to 32,767).
    • Too large: "99999"
    • Too small: "-99999"

Example of an Error

public class StringToShortErrorExample {
    public static void main(String[] args) {
        String invalidStr1 = "hello";
        String invalidStr2 = "99999"; // Too large for a short
        String emptyStr = "";
        System.out.println("Trying to convert: '" + invalidStr1 + "'");
        try {
            Short.parseShort(invalidStr1);
        } catch (NumberFormatException e) {
            System.out.println("  -> Caught expected exception: " + e.getMessage());
        }
        System.out.println("\nTrying to convert: '" + invalidStr2 + "'");
        try {
            Short.parseShort(invalidStr2);
        } catch (NumberFormatException e) {
            System.out.println("  -> Caught expected exception: " + e.getMessage());
        }
        System.out.println("\nTrying to convert: '" + emptyStr + "'");
        try {
            Short.parseShort(emptyStr);
        } catch (NumberFormatException e) {
            System.out.println("  -> Caught expected exception: " + e.getMessage());
        }
    }
}

Output:

Java字符串如何转Short类型?-图3
(图片来源网络,侵删)
Trying to convert: 'hello'
  -> Caught expected exception: For input string: "hello"
Trying to convert: '99999'
  -> Caught expected exception: Value out of range. Value:"99999" Radix:10
Trying to convert: ''
  -> Caught expected exception: For input string: ""

Alternative: Short.valueOf()

This method is very similar to parseShort(), but it returns a Short object (a wrapper class) instead of a primitive short. This is useful when you need an object, for example, in collections that don't accept primitives like ArrayList<Short>.

Syntax

public static Short valueOf(String s) throws NumberFormatException
public static Short valueOf(String s, int radix) throws NumberFormatException

Example

public class ValueOfExample {
    public static void main(String[] args) {
        String strNumber = "255";
        Short shortObject = Short.valueOf(strNumber); // Returns a Short object
        System.out.println("The object is: " + shortObject);
        System.out.println("The type of the object is: " + shortObject.getClass().getName());
        // You can easily get the primitive value back
        short primitiveValue = shortObject; // Auto-unboxing
        System.out.println("The primitive value is: " + primitiveValue);
    }
}

Output:

The object is: 255
The type of the object is: java.lang.Short
The primitive value is: 255

Summary: Which Method to Use?

Method Return Type When to Use
Short.parseShort(String s) short (primitive) Best for most cases. Use when you need the primitive type for calculations or performance-critical code.
Short.parseShort(String s, int radix) short (primitive) Use when the number is in a non-decimal format (binary, octal, hex).
Short.valueOf(String s) Short (object) Use when you need an Short object, such as for generics or when working with APIs that require objects.
Short.valueOf(String s, int radix) Short (object) Use when you need an object from a non-decimal string.

Key Takeaway: Always wrap your conversion logic in a try-catch block if there's any possibility that the input String might not be a valid short. This prevents your program from crashing unexpectedly.

分享:
扫描分享到社交APP
上一篇
下一篇