Qas*_*iaz 20 java arrays while-loop numberformatexception
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)
Run Code Online (Sandbox Code Playgroud)
我的循环:
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
Run Code Online (Sandbox Code Playgroud)
xen*_*ros 37
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
Run Code Online (Sandbox Code Playgroud)
手段:
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
Run Code Online (Sandbox Code Playgroud)
换句话说,你试图解析"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
}
}
Run Code Online (Sandbox Code Playgroud)
ExceptionJava?例外是在程序执行期间发生的事件,它会破坏程序指令的正常流程.
- 文件
Integer#parseIntstatic NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
public NumberFormatException (String s) {
super (s);
}
Run Code Online (Sandbox Code Playgroud)
它们对于理解如何读取堆栈跟踪非常重要.看看是如何NumberFormatException抛出的Integer#parseInt:
if (s == null) {
throw new NumberFormatException("null");
}
Run Code Online (Sandbox Code Playgroud)
或者以后,如果输入的格式String s不可解析:
throw NumberFormatException.forInputString(s);
Run Code Online (Sandbox Code Playgroud)
NumberFormatException?抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式.
- 文件
NumberFormatException extends IllegalArgumentException.它告诉我们它更专业IllegalArgumentException.实际上,它用于突出显示虽然,参数类型是正确的(String),但是内容String不是数字(a,b,c,d,e,f在HEX中被认为是数字,并且在需要时是合法的).
我如何解决它?
好吧,不要解决它抛出的事实.抛出它是件好事.有些事情你需要考虑:
String这导致了Exception一个null?消息的第一行是异常发生的信息和String导致问题的输入.字符串始终跟随:并引用("some text").然后你有兴趣从最后读取堆栈跟踪,因为前几行通常NumberFormatException是构造函数,解析方法等.然后在最后,你有一个方法,你在其中制造了一个bug.将在其调用的文件和方法中指出.即使是一条线也会被附加.你会看到的.上面是如何读取堆栈跟踪的示例.
当你看到,而不是"For input string:"和输入,有一个null(不"null")意味着,你试图将空引用传递给一个数字.如果您真的想要处理为0或任何其他数字,您可能会对我在StackOverflow上的另一篇文章感兴趣.它可以在这里找到.
null在StackOverflow线程中很好地描述了解决意外s的描述什么是NullPointerException以及如何解决它?.
如果您所String看到的:并且被引用的内容看起来像一个数字,则可能存在您的系统无法解码的字符或看不见的空格.显然" 6"无法解析以及不能解析"123 ".这是因为空间.但它可能String会出现,看起来会像,"6"但实际上它的长度将大于你可以看到的数字位数.
在这种情况下,我建议使用调试器或至少System.out.println打印String您尝试解析的长度.如果它显示的位数超过了数字,请尝试传递stringToParse.trim()给解析方法.如果它不起作用,请复制整个字符串,:然后使用在线解码器对其进行解码.它会给你所有字符的代码.
最近我发现了一个案例StackOverflow,你可能会看到,输入看起来像一个数字,例如"1.86"它只包含那4个字符,但错误仍然存在.请记住,只能用#Integer#parseInt#解析整数.对于解析十进制数,应该使用Double#parseDouble.
另一种情况是,当数字有多位数时.它可能是,它太大或太小而不适合int或long.你可能想尝试一下new BigDecimal(<str>).
最后,我们来到了我们同意的地方,当用户输入"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.
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*tto 10
NumberFormatException?抛出此异常表示应用程序已尝试将a转换
string为其中一种数字类型,但string它没有适当的格式.
在您的情况下,根据您的堆栈跟踪,抛出此异常,Integer.parseInt(String)这意味着提供的String不包含可解析的integer.仍然根据堆栈跟踪,这是因为你试图将String " Ace of Clubs " 解析为一个整数,它不能工作,因为它不是String整数的表示.
最简单和通用的方法是捕获异常 NumberFormatException
int value = -1;
try {
value = Integer.parseInt(myString);
} catch (NumberFormatException e) {
// The format was incorrect
}
Run Code Online (Sandbox Code Playgroud)
它会起作用,但是捕获异常很慢,因为它需要构建调用堆栈以创建Exception成本很高的,所以如果你能避免它那么做.此外,您需要正确管理异常,这并不总是很明显.
或者你可以使用a regular expression先检查是否String matches有一个Integer但是它很容易出错,因为你很容易使用错误regular expression.
在您的情况下,应该使用更多OO方法而不是处理String,例如,您可以使用a class或an enum来表示您的卡而不是使用简单,String因为它更容易出错,因为您已经注意到了.
因此,如果您决定为您的卡使用专用课程,您的代码可能是:
public class Card {
private final Rank rank;
private final Suit suit;
public Card(final Rank rank, final Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank getRank() {
return this.rank;
}
public Suit getSuit() {
return this.suit;
}
}
Run Code Online (Sandbox Code Playgroud)
对于卡片的套装和等级,我们可以使用,enum因为现有的等级和套装数量有限.
public enum Rank {
ACE(1), TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), HEIGHT(8),
NINE(9), TEN(10), JACK(11), QUEEN(12), KING(13);
private final int value;
Rank(final int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
public enum Suit {
SPADE, HEART, DIAMOND, CLUB
}
Run Code Online (Sandbox Code Playgroud)
然后cards将是一个数组Card而不是数组String,并可以初始化为下一个:
Rank[] ranks = Rank.values();
Suit[] suits = Suit.values();
Card[] cards = new Card[ranks.length * suits.length];
for (int i = 0; i < ranks.length; i++) {
for (int j = 0; j < suits.length; j++) {
cards[i * suits.length + j] = new Card(ranks[i], suits[j]);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要洗牌你的卡片,你可以继续下一步(请注意,如果你决定使用一张List卡而不是一个阵列只需使用Collections.shuffle(list))
List<Card> allCards = Arrays.asList(cards);
Collections.shuffle(allCards);
allCards.toArray(cards);
Run Code Online (Sandbox Code Playgroud)
然后,您将能够直接访问您的卡的价值,cards[index].getRank().getValue()而不会冒险获得异常(IndexOutOfBoundsException如果您没有使用正确的索引,则除外).
小智 6
貌似cards[]是字符串数组,你正试图转换Ace of Clubs到整数.
int first_value = Integer.parseInt(cards[index]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32648 次 |
| 最近记录: |