【问题标题】:Having trouble with implementing a system that detects if an input is a integer or not无法实现检测输入是否为整数的系统
【发布时间】:2020-05-31 05:17:53
【问题描述】:

我正在尝试创建一个系统,询问用户他们希望一个短语重复多少次,然后它会检查答案是整数还是字符串。当我不尝试实现这个系统并且只询问短语以及应该重复多少次时,该程序运行良好,但是当我尝试检查次数是否为整数时,它会变得很糟糕。

import java.util.*;

public class Phrase {
    public static Scanner phraseScan = new Scanner (System.in);
    public static Scanner amountScan = new Scanner (System.in);
    public static void main (String[] args ) {

        System.out.println("What phrase do you want repeated?");
        String phrase = phraseScan.nextLine();
        int phraseLoops = 0;

        System.out.println("How many " + phrase + "s" + " do you want?");
        int desiredPhraseLoops = amountScan.nextInt();

        for (;;) {
            if (!amountScan.hasNextInt()) {
                System.out.println("Integers only please");
                amountScan.next();

            }
            desiredPhraseLoops = amountScan.nextInt();
            if (desiredPhraseLoops >= 0) {
                System.out.println("Valid amount!");
                continue;
            } else {
                break;

            }
        }



        System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");

        do {
            System.out.println(phrase);
            phraseLoops++;

        } while (phraseLoops != desiredPhraseLoops);

        System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
    }
}

我尝试过的:

try {
          desiredPhraseLoops = amountScan.nextInt();

        } catch (InputMismatchException exception) {
            System.out.println("This is not an integer.");
        } 

          if (!amountScan.hasNextInt()) {
            System.out.println("Good.");
        } else {
            System.out.println("Enter an Integer please.");
        } 

每当我尝试任何事情时,它都会询问我想要哪个短语以及我希望它重复多少次。然后程序就停止了,不管我输入一个整数还是一个字符串,它都没有给我任何其他提示。

输出是这样的:

你想重复哪个短语? 测试 你想要多少个测试? 3

就是这样。

【问题讨论】:

    标签: java input integer


    【解决方案1】:

    首先,只需使用一个 Scanner 对象。您不需要更多的键盘输入。

    如果你喜欢,你可以坚持使用 Scanner#nextLine() 方法,例如:

    Scanner userInput = new Scanner(System.in); 
    
    String phrase = "";
    while (phrase.equals("")) {
        System.out.println("What phrase do you want repeated?");
        phrase = userInput.nextLine();
        // VALIDATION: 
        // Was anything other than a empty string (spaces) 
        // or longer than 2 characters supplied?
        if (phrase.trim().equals("") || phrase.length() < 3) {
            // Nope!
            System.err.println("Invalid Input!. Enter a proper phrase!");
            phrase = "";
        }
        // Yes, allow the prompt loop to exit.
    }
    
    String phraseLoopsNumber = "";
    while (phraseLoopsNumber.equals("")) {
        System.out.println("How many " + phrase + "s" + " do you want?");
        phraseLoopsNumber = userInput.nextLine();
        // VALIDATION: 
        // Did the User supply a string representation of an integer value? 
        if (!phraseLoopsNumber.matches("\\d+")) {
            // Nope!
            System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
            phraseLoopsNumber = "";
        }
        // Yes he/she/it did...Allow prompt loop to exit.
    }
    
    int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
    
    // Do what you have to do with the desired number of loops contained
    // within the numberOfLoops integer variable.
    

    在上面的代码中,String#matches() 方法与一个小的 Regular Expression (RegEx) 一起使用。传递给 ma​​tches() 方法的 "\\d" 表达式检查它所处理的字符串是否包含所有(1 个或多个)数字。

    如果您一心想要使用 Scanner#nextInt() 方法,那么您可以这样做:

    int numberOfLoops = -1;
    while (numberOfLoops == -1) {
        System.out.println("How many " + phrase + "'s" + " do you want?");
        // Trap any input errors against the Scanner.nextInt() method... 
        // This would be a form of validation.
        try {
            numberOfLoops = userInput.nextInt();
            // Consume the newline from ENTER key in case a nextLine() prompt is next.
            userInput.nextLine(); 
        } catch (Exception ex) {
            System.out.println("Invalid Input! An integer value is expected!");
            // Consume the newline from ENTER key in case a nextLine() prompt is next.
            // The first one above would of been skipped past if nextInt() threw an exception.
            userInput.nextLine(); 
            numberOfLoops = -1;
            continue;  // continue loop so as to re-prompt
        }
        // Further Validation: 
        // Did the User supply a number greater than 0? 
        if (numberOfLoops < 1 ) {
            // Nope!
            System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
            numberOfLoops = -1; 
        }
        // Yes he/she did...Allow prompt loop to exit.
    }
    // Do what you have to do with the desired number of loops contained
    // within the numberOfLoops integer variable. 
    

    【讨论】:

    • 谢谢,这两种方法都对我有用。但是,我不太明白为什么第二种方法中循环数以-1开头,而不是从0开始?
    • 只是一种习惯。通常 0 是一个有效且所需的值,但在这种特殊情况下它不是,因此可以用来代替 -1。
    猜你喜欢
    • 2012-09-23
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多