我想從用戶那里獲取稅號并檢查我得到的號碼是否正確但我有問題。當我運行程式時,如果用戶首先給出錯誤的號碼(一個少于或多于九位的數字)我看到我寫的訊息是正確的,但是當用戶在一些輸入后給出正確的數字時,我再次看到訊息并且回圈永遠不會停止。如果有人可以幫助我,我會很感激,因為我被卡住了:)
在此處輸入影像描述 在此處 輸入影像描述
uj5u.com熱心網友回復:
當您在while回圈中第二次獲得輸入時會出現問題......因為您實際上并沒有再次檢查 TIN 號碼。我建議您創建一個函式來檢查 TIN 是否有效并使用 while 回圈不斷獲取輸入
像這樣:
public static void main(String[] args) {
System.out.println("Give me your TIN number");
Scanner in = new Scanner(System.in);
long TIN = in.nextLong();
//while the input is not valid ("!" negates the boolean) print invalid input and get the input again
while(!isValidTIN(TIN)){
System.out.println("Wrong number! Try Again");
TIN = in.nextLong();
};
// Countinue with your program
System.out.println("Success");
}
public static boolean isValidTIN(long TIN){
int count = 0;
while(TIN > 0){
TIN /= 10; //You can also use TIN /= 10 instead of TIN = TIN / 10
count ;
}
return count == 9;
}
下次還要粘貼代碼而不是影像
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487840.html
