简体   繁体   English

如何在同一行读取 int 和 string? Java 扫描仪 class

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

I must ask the user to enter a province and number for 0-100 on the same line.我必须要求用户在同一行输入 0-100 的省份和编号。

Here's the code:这是代码:

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();
    
    }
}

I want the input to take in both the prov and tax on the same line despite them being different data types.尽管它们是不同的数据类型,但我希望输入在同一行中同时接收 prov 和 tax。 The code seems to still take in the values at different lines.该代码似乎仍然采用不同行的值。

Input Example: NY 15输入示例:NY 15

where NY represents the prov variable and the "15" represents the tax variable.其中 NY 代表prov变量,“15”代表 tax 变量。

Read an entire line and parse that instead of trying to read two values from a line.读取整行并解析它,而不是尝试从一行中读取两个值。 A complete example might look something like,一个完整的例子可能看起来像,

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);

This is just another option for this task which also contains User entry validation.这只是此任务的另一个选项,它还包含用户输入验证。 If the User enters the required data incorrectly then that User is informed of such and given the opportunity to attempt the entry again or enter q to quit.如果用户输入的数据不正确,则用户会收到此类通知,并有机会再次尝试输入或输入q退出。

The provided runnable demo below allows for single country state or province two letter abbreviations or overall North American (Canada, USA, and Mexico) abbreviations which the demo actually utilizes.下面提供的可运行演示允许演示实际使用的单个国家/地区 state 或省份两个字母缩写或整个北美(加拿大、美国和墨西哥)缩写。 The means to easily modify the demo code for a single specific country is only a few keystrokes away.轻松修改单个特定国家/地区的演示代码的方法仅需几次按键即可。

The tax rate is of double data type and the code validates User entry for unsigned integer or floating point values from 0 to 100 (percent) only.税率为double精度数据类型,代码仅验证用户输入的无符号 integer 或 0 到 100(百分比)的浮点值。 Floating point entry is allowed since US states contain a floating point sales tax rate .由于美国各州采用浮点销售税率,因此允许浮点输入。

When the entry prompt is displayed, the User is expected to enter a two letter abbreviation (in any letter case) of a state or province and on the same entry line, the tax rate for that same state or province separated with a whitespace or tab.显示输入提示时,用户应输入 state 或省份的两个字母缩写(任何字母大小写),并在同一输入行中输入相同 state 或省份的税率,以空格或制表符分隔. The following would be valid entries:以下将是有效条目:

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]

Invalid entries might be:无效条目可能是:

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)] 

Here is the runnable code:这是可运行的代码:

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 + "%");
    }
    
}

In the above code, the String#matches() method (along with a rather intense Regular Expression ) is used on the User entered string to carry out entry validation.在上面的代码中, String#matches()方法(连同相当强烈的Regular Expression )用于用户输入的字符串以执行输入验证。 The string variable regEx holds the Regular Expression used:字符串变量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