草庐IT

java - 什么是 NumberFormatException 以及如何修复它?

coder 2023-05-19 原文

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

我的while循环:
while (response != 'q' && index < 52) {
    System.out.println(cards[index]);
    int first_value = Integer.parseInt(cards[index]);
    int value = 0;
    //Add a Scanner
    Scanner scanner = new Scanner(System.in);
    System.out.println("Will the next card be higher or lower?, press q if you want to quit");
    String guess = scanner.nextLine();
    if(cards[index].startsWith("Ace")) { value = 1; }
    if(cards[index].startsWith("2")) { value = 2; }
    if(cards[index].startsWith("3")) { value = 3; }
    //checking 4-10
    if(cards[index].startsWith("Queen")){ value = 11; }
    if(cards[index].startsWith("King")){ value = 12; }
    if(guess.startsWith("h")){
        if(value > first_value){ System.out.println("You answer was right, weldone!"); } 
        else { System.out.println("You answer was wrong, try again!"); }
    } else if(guess.startsWith("l")){
        if(value < first_value) { System.out.println("You answer as right, try again!"); }
        else { System.out.println("You answer was wrong, try again!"); }
    } else { System.out.println("Your was not valid, try again!"); }
    scanner.close();            
    index++;
}//end of while loop

最佳答案

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

方法:
There was an error. We try to give you as much information as possible
It was an Exception in main thread. It's called NumberFormatException and has occurred for input "Ace of Clubs".
at line 65th of NumberFormatException.java which is a constructor,
which was invoked from Integer.parseInt() which is in file Integer.java in line 580,
which was invoked from Integer.parseInt() which is in file Integer.java in line 615,
which was invoked from method main in file Cards.java in line 68.

It has resulted in exit code 1

换句话说,你试图解析 "Ace of Clubs"int Java 不能用方法做什么 Integer.parseInt . Java 提供了漂亮的堆栈跟踪,它可以准确地告诉您问题是什么。您正在寻找的工具是 调试器 并使用 断点 将允许您在所选时刻检查应用程序的状态。

如果您想使用解析,解决方案可能是以下逻辑:
if (cards[index].startsWith("Ace")) 
    value = 1;
else if (cards[index].startsWith("King"))
    value = 12;
else if (cards[index].startsWith("Queen"))
    value = 11;
...
else {
    try {
        Integer.parseInt(string.substring(0, cards[index].indexOf(" "))); 
    } catch (NumberFormatException e){
        //something went wrong
    }
}

什么是Exception在 java ?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.



- Documentation
Integer#parseInt 中的构造函数和用法
static NumberFormatException forInputString(String s) {
    return new NumberFormatException("For input string: \"" + s + "\"");
}

public NumberFormatException (String s) {
    super (s);
}

它们对于理解如何阅读堆栈跟踪很重要。看看如何NumberFormatExceptionInteger#parseInt 抛出:
if (s == null) {
    throw new NumberFormatException("null");
}

或更高版本,如果输入格式 String s不可解析:
throw NumberFormatException.forInputString(s); 

什么是NumberFormatException ?

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.



- Documentation
NumberFormatException extends IllegalArgumentException .它告诉我们它更专业IllegalArgumentException .实际上,它用于强调尽管参数类型是正确的( String ) String 的内容不是数字(a、b、c、d、e、f 被认为是十六进制中的数字,在需要时是合法的)。

我如何解决它?
好吧,不要解决它被抛出的事实。扔了就好了。您需要考虑以下几点:
  • 我可以阅读堆栈跟踪吗?
  • String这会导致 Exception null ?
  • 它看起来像一个数字吗?
  • 它是“我的字符串”还是用户的输入?
  • 待续

  • 广告。 1.

    消息的第一行是异常发生的信息和输入String这导致了问题。字符串始终跟随 :并被引用( "some text" )。然后你开始对从最后阅读堆栈跟踪感兴趣,因为前几行通常是 NumberFormatException的构造函数,解析方法等。然后在最后,您的方法中出现了错误。将指出它是在哪个文件中调用的以及在哪个方法中调用的。甚至会附加一条线。你会看到的。上面是如何读取堆栈跟踪的示例。

    广告。 2.

    当你看到时,那不是 "For input string:"和输入,有一个 null (不是 "null" )这意味着,您试图将空引用传递给一个数字。如果您真的想将 is 视为 0 或任何其他数字,您可能会对我在 StackOverflow 上的另一篇文章感兴趣。有货 here .

    解决意外的说明null s 在 StackOverflow 线程 What is a NullPointerException and how can I fix it? 上有很好的描述.

    广告。 3.

    如果String跟随 :并且在您看来被引用看起来像一个数字,可能有一个您的系统无法解码的字符或一个看不见的空格。显然 " 6"无法解析为"123 "不能。这是因为空格。但可能会发生,String看起来像 "6"但实际上它的长度会大于你能看到的位数。

    在这种情况下,我建议使用 调试器 或至少 System.out.println并打印 String 的长度你正在尝试解析。如果显示的位数多于位数,请尝试通过 stringToParse.trim()到解析方法。如果不行,复制:后面的整个字符串并使用在线解码器对其进行解码。它会给你所有字符的代码。

    我最近在StackOverflow上发现了一个案例。 ,您可能会看到,输入看起来像一个数字,例如"1.86"它只包含那 4 个字符,但错误仍然存​​在。请记住,只能使用#Integer#parseInt# 解析整数。对于解析十进制数,应该使用 Double#parseDouble .

    另一种情况是,当号码有很多位数时。可能是它太大或太小而无法容纳 intlong .您可能想尝试 new BigDecimal(<str>) .

    广告。 4.

    最后我们来到了我们同意的地方,我们无法避免用户输入“abc”作为数字字符串的情况。为什么?因为他可以。幸运的是,那是因为他是测试人员,或者只是个极客。在最坏的情况下,它是攻击者。

    我现在能做什么?好吧,Java 给了我们 try-catch您可以执行以下操作:
    try {
        i = Integer.parseInt(myString);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        //somehow workout the issue with an improper input. It's up to your business logic.
    }
    

    关于java - 什么是 NumberFormatException 以及如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39849984/

    有关java - 什么是 NumberFormatException 以及如何修复它?的更多相关文章

    1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

      我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

    2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

      类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

    4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

      给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

    6. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

      我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

    7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

      我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

    8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

      我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

    9. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

      我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

    10. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

      我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

    随机推荐