Java/Data Type/Convert from String

Материал из Java эксперт
Перейти к: навигация, поиск

Convert from String to integer

  
public class Main {
  public static void main(String[] args) throws Exception {
    String str = "25";
    int i = Integer.valueOf(str).intValue();
    // or
    i = Integer.parseInt(str);
  }
}





Converting a String to a byte Number

 
public class Main {
  public static void main(String[] argv) throws Exception {
    byte b = Byte.parseByte("123");
    System.out.println(b);
  }
}





Converting a String to a int(integer) Number

 
public class Main {
  public static void main(String[] argv) throws Exception {
    int i = Integer.parseInt("123");
    System.out.println(i);
  }
}





Converting a String to a short Number

 
public class Main {
  public static void main(String[] argv) throws Exception {
    short s = Short.parseShort("123");
    System.out.println(s);
  }
}





Convert string to an integer or number

  
 
public class Main {
  public static void main(String[] args) {
    String myNumber = "13";
    Integer number = Integer.parseInt(myNumber);
    System.out.println("My lucky number is: " + number);
    number = Integer.parseInt(myNumber, 16);
    System.out.println("My lucky number is: " + number);
    number = Integer.parseInt(myNumber, 8);
    System.out.println("My lucky number is: " + number);
  }
}





Declaring Checked Exceptions

  

public class Main {
  public void convertStringToInt() throws NumberFormatException {
    String s = "123";
    int number = Integer.parseInt(s);
  }
}





Decode string to integer

  
 
public class Main {
  public static void main(String[] args) {
    String decimal = "10"; // Decimal
    String hexa = "0XFF"; // Hexa
    String octal = "077"; // Octal
    Integer number = Integer.decode(decimal);
    System.out.println("String [" + decimal + "] = " + number);
    number = Integer.decode(hexa);
    System.out.println("String [" + hexa + "] = " + number);
    number = Integer.decode(octal);
    System.out.println("String [" + octal + "] = " + number);
  }
}





Parse and format a number to decimal

  
public class Main {
  public static void main(String[] argv) throws Exception {
    int i = Integer.parseInt("1023");
    String s = Integer.toString(i);
    System.out.println(s);
  }
}





Parse and format a number to octal

  

public class Main {
  public static void main(String[] argv) throws Exception {
    int i = Integer.parseInt("1000", 8);
    String s = Integer.toString(i, 8);
    System.out.println(s);
  }
}





Parse and format to arbitrary radix <= Character.MAX_RADIX

  
public class Main {
  public static void main(String[] argv) throws Exception {
    int radix = 32;
    int i = Integer.parseInt("vv", radix);
    String s = Integer.toString(i, radix);
  }
}





Parse and format to hexadecimal

  
public class Main {
  public static void main(String[] argv) throws Exception {
    int i = Integer.parseInt("3ff", 16);
    String s = Integer.toString(i, 16);
    System.out.println(s);
  }
}





Parse a number using a NumberFormat

  
import java.text.NumberFormat;
import java.text.ParseException;
/*
 * Parse a number using a NumberFormat.
 */
public class NumFormatParse {
  //+
  /** A number to parse */
  public static final String input = "4096.251";
  //-
  /** The main (and only) method in this class. */
  public static void main(String[] av) { 
    //+
    NumberFormat defForm = NumberFormat.getInstance();
    try {
      Number d = defForm.parse(input);
      System.out.println(input + 
        " parses as " + d +
        " and formats as " + defForm.format(d));
    } catch (ParseException pe) {
      System.err.println(input + "not parseable!");
    }
    //-
  }
}





Pass a string to the Integer class constructor and call the intValue()

  
public class Main {
  public static void main(String[] argv) {
    String sValue = "5";
    try {
      int iValue = new Integer(sValue).intValue();
    } catch (NumberFormatException ex) {
      ex.printStackTrace();
    }
  }
}





Validate if string is a number

  
public class Main {
  public static boolean checkIfNumber(String in) {
    try {
      Integer.parseInt(in);
    } catch (NumberFormatException ex) {
      return false;
    }
    return true;
  }
  public static void main(String[] args) {
    System.out.println(checkIfNumber("ABC"));
    System.out.println(checkIfNumber("123123123123123"));
  }
}





Value Of Demo

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class ValueOfDemo {
  public static void main(String[] args) {
    //this program requires two arguments on the command line
    if (args.length == 2) {
      //convert strings to numbers
      float a = Float.valueOf(args[0]).floatValue();
      float b = Float.valueOf(args[1]).floatValue();
      //do some arithmetic
      System.out.println("a + b = " + (a + b));
      System.out.println("a - b = " + (a - b));
      System.out.println("a * b = " + (a * b));
      System.out.println("a / b = " + (a / b));
      System.out.println("a % b = " + (a % b));
    } else {
      System.out
          .println("This program requires two command-line arguments.");
    }
  }
}