簡體   English   中英

如何在同一行讀取 int 和 string? Java 掃描儀 class

[英]how to read int and string at the same line? Java Scanner class

我必須要求用戶在同一行輸入 0-100 的省份和編號。

這是代碼:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String prov = in.next();
        int tax = in.nextInt();
    
    }
}

盡管它們是不同的數據類型,但我希望輸入在同一行中同時接收 prov 和 tax。 該代碼似乎仍然采用不同行的值。

輸入示例:NY 15

其中 NY 代表prov變量,“15”代表 tax 變量。

讀取整行並解析它,而不是嘗試從一行中讀取兩個值。 一個完整的例子可能看起來像,

Scanner in = new Scanner(System.in);
String line = in.nextLine();
String prov = line.substring(0, line.indexOf(' '));
int tax = Integer.parseInt(line.substring(prov.length() + 1));
System.out.printf("prov = %s, tax = %d%n", prov, tax);

這只是此任務的另一個選項,它還包含用戶輸入驗證。 如果用戶輸入的數據不正確,則用戶會收到此類通知,並有機會再次嘗試輸入或輸入q退出。

下面提供的可運行演示允許演示實際使用的單個國家/地區 state 或省份兩個字母縮寫或整個北美(加拿大、美國和墨西哥)縮寫。 輕松修改單個特定國家/地區的演示代碼的方法僅需幾次按鍵即可。

稅率為double精度數據類型,代碼僅驗證用戶輸入的無符號 integer 或 0 到 100(百分比)的浮點值。 由於美國各州采用浮點銷售稅率,因此允許浮點輸入。

顯示輸入提示時,用戶應輸入 state 或省份的兩個字母縮寫(任何字母大小寫),並在同一輸入行中輸入相同 state 或省份的稅率,以空格或制表符分隔. 以下將是有效條目:

QC 14.975       [Quebec, Canada]
MO 8.25         [Missouri, USA or Morelos, Mexico]
bc    12        [British Columbia, Canada or Baja California, Mexico]
sk 11           [Saskatchewan, Canada]
ON  13          [Ontario, Canada]
GR 0            [Guerrero, Mexico]
q               [Used to quit the application]

無效條目可能是:

QC14.975        [No whitespace]
MO, 8.25        [comma used]
ZA 6f           [A non-digit in tax rate] 
bv    12        [No such state or province]
sk 101          [Tax rate out of range (0 to 100 allowed only)]
ON  -13         [signed tax rate value]
7.5             [no state or province supplied]
YU              [no tax rate supplied (minimum 0 to be supplied)]
                [nothing supplied (just Enter key was hit)] 

這是可運行的代碼:

public class StateProvinceAbbrevAndTaxRateDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        java.util.Scanner in = new java.util.Scanner(System.in);
        
        /* North American Postal Abbreviations used for entry validation...
           Select your flavor or use all three as used in this demo:                       */
        String canada = "\\bnl|pe|ns|nb|qc|on|mb|sk|ab|bc|yt|nt|nu\\b";
        
        String usa = "\\bAL|AK|AZ|AR|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|"
                   + "ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|"
                   + "PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY\\b";
        
        String canadaUSA = "\\bAL|AK|AZ|AR|AB|BC|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|"
                          + "IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|MB|NE|NV|NH|NJ|"
                          + "NM|NY|NC|ND|NL|NS|NB|NT|NU|OH|OK|OR|ON|PA|PE|QC|RI|"
                          + "SC|SD|SK|TN|TX|UT|VT|VA|WA|WV|WI|WY|YT\\b";
        
        String mexico = "\\bAG|BC|BS|CM|CS|CH|CO|CL|DF|DG|GT|GR|JA|EM|MI|MO|"
                      + "NA|NL|OA|PU|QT|QR|SL|SI|SO|TB|TM|TL|VE|YU|ZA\\b";
        // =======================================================================
        
        /* Used for entry Validation:
           Desired abbreviations added to Regular Expression (regex).
           The regex below covers abbreviations for all of North America 
           (Canada/USA/Mexico). Modify the expression to suit your needs.   */
        String regEx = "(?i)q|(" + canada + "|" + usa + "|" + mexico + ")" // valid abbbreviation
                     + "\\s+"                                              // must have 'at least' one space (could have more)... 
                     + "(\\b([0-9]|[1-9][0-9]|100)(\\.\\d*)?\\b)";         // tax rate must be inclusively between 0 and 100 percent.
        String input = "";
        while (input.isEmpty()) {
            System.out.println("Enter the state or province postal abbreviation and tax");
            System.out.println("rate separated with a space (ex: BC 7 or: ny 8.52).");
            System.out.print(  "Enter 'Q' to quit: --> ");
            input = in.nextLine();
            if (!input.matches(regEx)) {
                System.out.println("Invalid Entry (" + input + ")! Please try again...");
                System.out.println();
                input = "";
            }
        }
        System.out.println();
        
        // Is 'q' (to quit) supplied?
        if (input.equalsIgnoreCase("q")) {
            System.out.println("Quitting... Bye-Bye");
            System.exit(0);
        }
        /* Split the User's data entry into a String Array  */
        String[] inputParts = input.split("\\s+");
        
        /* Apply the String Array elements to their respective 
           variables (converting where required).          */
        String stateProv = inputParts[0].toUpperCase();
        double tax = Double.parseDouble(inputParts[1]);
        
        // Display results within the Console Window.
        System.out.println("State/Province: --> " + stateProv);
        System.out.println("Tax Rate:       --> " + tax + "%");
    }
    
}

在上面的代碼中, String#matches()方法(連同相當強烈的Regular Expression )用於用戶輸入的字符串以執行輸入驗證。 字符串變量regEx保存使用的正則表達式:

String regEx = "(?i)q|(" + canada + "|" + usa + "|" + mexico + ")" // valid abbbreviation
             + "\\s+"                                              // must have 'at least' one space (could have more)... 
             + "(\\b([0-9]|[1-9][0-9]|100)(\\.\\d*)?\\b)";         // tax rate must be inclusively between 0 and 100 percent.

暫無
暫無

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

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