簡體   English   中英

關於else語句(java)

[英]About else statements (java)

首先,問題如下:編寫一個程序,提示用戶以DDD-DD-DDDD格式輸入社會安全號碼,其中D是數字。 您的程序應檢查輸入是否有效。 這是示例運行:

Enter a SSN: 232-23-5435

232-23-5435 is a valid Social Security Number. 

另一個測試:

Enter a SSN: 23-23-5435

23-23-5435 is an invalid Social Security Number.

我的代碼如下:

import java.util.Scanner;

public class SSN {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter a Social Security Number in the format DDD-DD-DDDD: ");
    String ssn = input.nextLine();

    boolean correct = true;

    if (ssn.length() != 11) {
      correct = false;
    } else {
      if (!('0' <= ssn.charAt(0) && ssn.charAt(0) <= '9')) {
        correct = false;
      }
      if (!('0' <= ssn.charAt(1) && ssn.charAt(1) <= '9')) {
        correct = false;
      }
      if (!('0' <= ssn.charAt(2) && ssn.charAt(2) <= '9')) {
        correct = false;
      }
      if (ssn.charAt(3) != '-') {
        correct = false;
      }
      if (!('0' <= ssn.charAt(4) && ssn.charAt(4) <= '9')) {
        correct = false;
      }
      if (!('0' <= ssn.charAt(5) && ssn.charAt(5) <= '9')) {
        correct = false;
      }
      if (ssn.charAt(6) != '-') {
        correct = false;
      }
      if (!('0' <= ssn.charAt(7) && ssn.charAt(7) <= '9')) {
        correct = false;
      }
      if (!('0' <= ssn.charAt(8) && ssn.charAt(8) <= '9')) {
        correct = false;
      }
      if (!('0' <= ssn.charAt(9) && ssn.charAt(9) <= '9')) {
        correct = false;
      }
      if (!('0' <= ssn.charAt(10) && ssn.charAt(10) <= '9')) {
        correct = false;
      }
    }

    if (correct == true) {
      System.out.println(ssn + " is a valid Social Security Number.");
    } else {
      System.out.println(ssn + " is an ivalid Social Security Number.");
    }
  }
}

不過,這是在問了我的教授之后的正確答案。

但是,我仍然不明白為什么我需要在if語句之間使用else{}

如果我不使用else{} ,它將適用於正確的SSN,但是當我輸入無效內容時,將返回:

Please enter a Social Security Number in the format DDD-DD-DDDD: sd
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at SSN.main(SSN.java:22)

怎么了? 為什么在那里需要else 程序不是只檢查每個if語句,最后通過檢查correct是否為false來給出輸出嗎?

我的意思是,即使沒有其他內容,即使有更多的計算,但它不應該一樣嗎?

我很困惑,出了什么問題,請幫忙,謝謝!

首先if檢查輸入的長度是否正確。 如果不是,它將不會檢查其他條件。

如果刪除else ,那么將檢查所有條件。 因此,如果您有5個長度的輸入,則在訪問第六個字符時會得到StringIndexOutOfBoundsException

您可以使用Pattern.compile(regex) ,然后檢查regex是否與您的輸入匹配,而不是編寫unclean code ifs這樣的unclean code ifs

因為您正在嘗試讀取一個不存在的字符。 如果您輸入的String少於9個字符,則以下代碼將引發StringIndexOutOfBoundsException

ssn.charAt(8)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM