Java Integer getInteger(String, Integer)方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-getintegerstring-integer-val-method

Integer类的 Java getInteger(String, Integer)方法也用于确定与作为字符串参数传递的系统属性相关联的整数值。这里的第二个参数也是默认值,但是返回的不是默认值,而是默认的 Integer 对象。

语法:

public static Integer getInteger(String nm, Integer val)

参数:

传递的参数是String nmInteger val,前者的系统属性整数值有待确定,后者是默认的整数对象,如果没有找到系统属性,将返回该对象。

返回:

如果没有与字符串关联的系统属性,则为与传递的字符串或默认整数对象的系统属性关联的整数值。

例 1:

这里,对于字符串 s,返回系统属性的整数值,对于没有系统属性值或名称的字符串,返回默认的 integer 对象。

import java.lang.Integer;

public class StudyTonight 
{  
    public static void main(String[] args)
    {  

        System.out.println(Integer.getInteger("java.vm.specification.vendor", 25));// Print default system property   

        System.out.println("Default value is:"+ Integer.getInteger("sun.arch.data.model")); //Prints the system property 

        // setting and printing the custom property  
        System.setProperty("studytonight.java", "80");  

        System.out.println("Custom Property: " + Integer.getInteger("studytonight.java"));  

        //printing a custom property which is not set will yield default value
        System.out.println("Custom Property: " + Integer.getInteger("mohit", 90));  

    }  
}

25 默认值为:64 自定义属性:80 自定义属性:90

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.util.Scanner; 

public class StudyTonight
{  
    public static void main(String[] args) 
    {          

        try
        {
           System.out.println("Enter the value and default value ");                   
           Scanner sc = new Scanner(System.in);  
           String s = sc.next();
           Integer i= sc.nextInt(); //Integer object for default value
           System.out.println("Value is : "+Integer.getInteger(s, i)); //will returns the integer value of the system property 

        }
        catch(Exception e)
        {

        }
    }  
}

输入数值和默认值 莫希特 23 数值为:23 *输入数值和默认值 sun.arch.model.data 87 数值为:87

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。