热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何判断Java整数是否为空?-HowcanItellifaJavaintegerisnull?

Greetings,Imtryingtovalidatewhethermyintegerisnull.Ifitis,Ineedtoprompttheusert

Greetings,

I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:

我正在尝试验证我的整数是否为空。如果是,我需要提示用户输入值。我的背景是Perl,所以我的第一次尝试看起来像这样:

int startIn = Integer.parseInt (startField.getText());

if (startIn) { 
    JOptionPane.showMessageDialog(null,
         "You must enter a number between 0-16.","Input Error",
         JOptionPane.ERROR_MESSAGE);                
}

This does not work, since Java is expecting boolean logic.

这不起作用,因为Java期望布尔逻辑。

In Perl, I can use "exists" to check whether hash/array elements contain data with:

在Perl中,我可以使用“exists”来检查散列/数组元素是否包含以下数据:

@items = ("one", "two", "three");
#@items = ();

if (exists($items[0])) {
    print "Something in \@items.\n";
}
else {
    print "Nothing in \@items!\n";
}

Is there a way to this in Java? Thank you for your help!

在Java中有这种方法吗?谢谢您的帮助!

Jeremiah

P.S. Perl exists info.

附: Perl存在信息。

7 个解决方案

#1


41  

parseInt() is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:

如果解析无法成功完成,parseInt()将抛出异常。您可以改为使用相应的对象类型Integers,这样可以使事情变得更加清晰。所以你可能想要更接近的东西:

Integer s = null;

try { 
  s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
  // ...
}

if (s != null) { ... }

Beware if you do decide to use parseInt()! parseInt() doesn't support good internationalization, so you have to jump through even more hoops:

请注意,如果您决定使用parseInt()! parseInt()不支持良好的国际化,所以你必须跳过更多的箍:

try {
    NumberFormat nf = NumberFormat.getIntegerInstance(locale);
    nf.setParseIntegerOnly(true);
    nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.

    // Start parsing from the beginning.
    ParsePosition p = new ParsePosition(0);

    int val = format.parse(str, p).intValue();
    if (p.getIndex() != str.length()) {
        // There's some stuff after all the digits are done being processed.
    }

    // Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
    // Something blew up in the parsing.
}

#2


8  

Try this:

Integer startIn = null;

try {
  startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
  .
  .
  .
}

if (startIn == null) {
  // Prompt for value...
}

#3


3  

ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.

整数是价值类型;他们永远不会是空的。相反,如果解析失败,parseInt将抛出您需要捕获的NumberFormatException。

#4


2  

There is no exists for a SCALAR in Perl, anyway. The Perl way is

无论如何,Perl中没有SCALAR。 Perl的方式是

defined( $x ) 

and the equivalent Java is

和等效的Java是

anInteger != null

Those are the equivalents.

那些是等价物。

exists $hash{key}

Is like the Java

就像Java一样

map.containsKey( "key" )

From your example, I think you're looking for

从你的例子来看,我认为你正在寻找

if ( startIn != null ) { ...

if(startIn!= null){...

#5


2  

For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:

对我来说,只使用Integer.toString()方法对我来说很好。如果只是想要它,那么你可以将它转换为null。示例如下:

private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null ||     Integer.toString(greenIn) == null )

#6


0  

I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.

我认为你不能在Perl中的整数上使用“exists”,只能在集合上使用。你能举例说明你在Perl中的意思与Java中的例子相符吗?

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

给定一个指定哈希元素或数组元素的表达式,如果哈希值或数组中的指定元素已被初始化,则返回true,即使相应的值未定义。

This indicates it only applies to hash or array elements!

这表明它只适用于散列或数组元素!

#7


0  

This should help.

这应该有所帮助。

Integer startIn = null;

// (optional below but a good practice, to prevent errors.)
boolean dOntContinue= false;
try {
  Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
  e.printStackTrace();
}

// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
  JOptionPane.showMessageDialog(null,
       "You must enter a number between 0-16.","Input Error",
       JOptionPane.ERROR_MESSAGE);                            
}

// (again optional)
if (dOntContinue== true) {
  //Do-some-error-fix
}

推荐阅读
  • Iamtryingtocreateanarrayofstructinstanceslikethis:我试图创建一个这样的struct实例数组:letinstallers: ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 转载:MFC 获得各类指针、句柄的方法
    2019独角兽企业重金招聘Python工程师标准转载:最近有些人在问MFC编程一些要点,有一些句柄的获取、指针的获取是 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 利用Visual Basic开发SAP接口程序初探的方法与原理
    本文介绍了利用Visual Basic开发SAP接口程序的方法与原理,以及SAP R/3系统的特点和二次开发平台ABAP的使用。通过程序接口自动读取SAP R/3的数据表或视图,在外部进行处理和利用水晶报表等工具生成符合中国人习惯的报表样式。具体介绍了RFC调用的原理和模型,并强调本文主要不讨论SAP R/3函数的开发,而是针对使用SAP的公司的非ABAP开发人员提供了初步的接口程序开发指导。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • 本文介绍了在iOS开发中使用UITextField实现字符限制的方法,包括利用代理方法和使用BNTextField-Limit库的实现策略。通过这些方法,开发者可以方便地限制UITextField的字符个数和输入规则。 ... [详细]
  • 本文介绍了RxJava在Android开发中的广泛应用以及其在事件总线(Event Bus)实现中的使用方法。RxJava是一种基于观察者模式的异步java库,可以提高开发效率、降低维护成本。通过RxJava,开发者可以实现事件的异步处理和链式操作。对于已经具备RxJava基础的开发者来说,本文将详细介绍如何利用RxJava实现事件总线,并提供了使用建议。 ... [详细]
  • 十大经典排序算法动图演示+Python实现
    本文介绍了十大经典排序算法的原理、演示和Python实现。排序算法分为内部排序和外部排序,常见的内部排序算法有插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等。文章还解释了时间复杂度和稳定性的概念,并提供了相关的名词解释。 ... [详细]
  • 本文介绍了GTK+中的GObject对象系统,该系统是基于GLib和C语言完成的面向对象的框架,提供了灵活、可扩展且易于映射到其他语言的特性。其中最重要的是GType,它是GLib运行时类型认证和管理系统的基础,通过注册和管理基本数据类型、用户定义对象和界面类型来实现对象的继承。文章详细解释了GObject系统中对象的三个部分:唯一的ID标识、类结构和实例结构。 ... [详细]
  • 抽空写了一个ICON图标的转换程序
    抽空写了一个ICON图标的转换程序,支持png\jpe\bmp格式到ico的转换。具体的程序就在下面,如果看的人多,过两天再把思路写一下。 ... [详细]
  • ExcelApp#启动excel程序ExcelAppCreateOleObject(“Excel.Application”);#加载文件但不显示文件内容(true表 ... [详细]
  • C#DataGridView控件中数据导出到Excel方法一:usingSystem;usingSystem.Collections.Generic;usingSys ... [详细]
  • Winform中实现连接Mysql8使用mysqldump实现备份表的数据
    场景Winform中连接Mysql8并查询表中数据进行显示:https:blog.csdn.netBADAO_LIUMANG_QIZHIarticledetails12039598 ... [详细]
author-avatar
平和-3699
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有