[英]NumberFormatException when parsing negative integer
我正在編寫一個Java程序來確定數字是否是回文。
如果傳遞的參數是正整數,我的代碼將正常工作,但傳遞負整數時將引發NumberFormatException。
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at com.stu.Main.isPalindrome(Main.java:28)
at com.stu.Main.main(Main.java:7)
我從另一個stackoverflow線程中獲得了以下解決方案,這似乎是講師希望我們使用的解決方案,但是在while循環中,我假定由於負數始終小於0,因此它將脫離循環而不進行計算回文:
public static int reverse(int number)
{
int result = 0;
int remainder;
while (number > 0)
{
remainder = number % 10;
number = number / 10;
result = result * 10 + remainder;
}
return result;
}
因此,我在下面的解決方案中使用字符串來解決此問題。
注意:我們尚未拆分和正則表達式。
public class Main {
public static void main(String[] args) {
isPalindrome(-1221); // throws exception
isPalindrome(707); // works as expected - returns true
isPalindrome(11212); // works as expected - returns false
isPalindrome(123321);// works as expected - returns true
}
public static boolean isPalindrome(int number){
if(number < 10 && number > -10) {
return false;
}
String origNumber = String.valueOf(number);
String reverse = "";
while(number > 0) {
reverse += String.valueOf(number % 10);
number /= 10;
}
if(Integer.parseInt(origNumber) == Integer.parseInt(reverse)) {
System.out.println("The original number was " + origNumber + " and the reverse is " + reverse);
System.out.println("Number is a palindrome!");
return true;
}
else
System.out.println("The original number was " + origNumber + " and the reverse is " + reverse);
System.out.println("Sorry, the number is NOT a palindrome!");
return false;
}
}
我在這里找兩件事。
首先,在教師首選解決方案的情況下,如何解決while循環中出現負數的問題?
其次,如何解決我的解決方案中的NumberFormatException?
編輯:第三個問題。 如果我從不解析回int,為什么我的解決方案返回false?
if(Integer.parseInt(origNumber) == Integer.parseInt(reverse)) // works
至
if(origNumber == reverse) // does not work
謝謝!
好的,解決您的第一個和第二個問題的最簡單方法就是使用Math.abs(yourNumber)
消除負號, Math.abs(yourNumber)
此而已。 如,
The java.lang.Math.abs() returns the absolute value of a given argument.
If the argument is not negative, the argument is returned.
If the argument is negative, the negation of the argument is returned.
這將解決您的第一個和第二個問題。
談到第三個問題,如果您不轉換回整數,那么在比較需要使用equals()
方法的字符串時,將得到假,
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
希望有幫助!! ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.