Java Integer.getInteger(String, int)方法

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

Integer类的 java getInteger(String nm, int val)方法用于确定与作为字符串参数传递的系统属性相关联的整数值。第二个参数 val 是默认值,在以下情况下返回:

  • 不存在给定名称的属性。

  • 如果属性没有给出正确的数字格式

  • 或者,传递的属性为 null 或空。

语法:

public static Integer getInteger(String nm, int val)

参数:

传递的参数有String nmint val,其中String nm 的系统属性整数值待定,而int val是缺省值,如果找不到系统属性,将返回缺省值。

返回:

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

例 1:

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

import java.lang.Integer;

public class StudyTonight
{

   public static void main(String[] args)
   {

      String s = "sun.arch.data.model";
      System.out.println(Integer.getInteger(s, 0));//returns the integer value of the system property of string s

      System.out.println(Integer.getInteger("java.vm.specification.vendor", 100)); // will return the default value as string as there is no property of the given name

      System.out.println(Integer.getInteger("studytonight",0)); // will return the default value as string does not have a system property value
   }
}

64 100 0

例 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();
           int i= sc.nextInt();
           System.out.println("Default Value: "+Integer.getInteger(s, i)); //will returns the integer value of the system property 

        }
        catch(Exception e)
        {

        }

    }  
}

输入数值和默认值 莫希特 78 默认值:78

实时示例:

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