我正在編寫一個 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循環(huán)中我假設由于負數始終小于0,它將跳出循環(huán)而不計算回文: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; }}我在這里尋找兩件事。首先,在講師首選解決方案的情況下,如何解決while循環(huán)中的負數問題?其次,如何解決我的解決方案中的 NumberFormatException ?編輯:第三個問題。如果我從不解析回 int,為什么我的解決方案會返回 false?if(Integer.parseInt(origNumber) == Integer.parseInt(reverse)) // works到if(origNumber == reverse) // does not work謝謝!
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
好的,解決第一個和第二個問題的最簡單方法就是使用刪除負號,僅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").
希望有幫助??!;)
添加回答
舉報
0/150
提交
取消