Java 如何限制对扫描仪的输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24835445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:05:21  来源:igfitidea点击:

How to limit the input to the Scanner?

java

提问by user2453911

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int inputInt = checkInput(in, "Enter an integer and a base: ");
    int inputBase = checkInput(in, "");
}

public static int checkInput(Scanner in, String prompt) {
    System.out.print(prompt);
    while (!in.hasNextInt()) {
        in.next();
        System.out.println("Sorry, that is an invalid input.");
        System.out.print(prompt);
    }
    return in.nextInt();
}

This method works and doesn't return any bad input i.e., ; p "hello".

此方法有效并且不会返回任何错误的输入,即;p“你好”。

My question is how can I limit the number of inputs the scanner will read. Say I input 5 five % ;but I only want 5and fiveto be passed in to my method and the rest dropped.

我的问题是如何限制扫描仪将读取的输入数量。假设我输入,5 five % ;但我只想5并被five传递到我的方法中,其余的则丢弃。

I looked through the Java API but couldn't find a method that would limit the amount of user input accepted. Am I just missing it or is there another way to do this?

我查看了 Java API,但找不到可以限制接受的用户输入量的方法。我只是想念它还是有另一种方法可以做到这一点?

Edit: I have tried using the .length() method to limit the input but then that doesn't allow integers greater than the .length() parameter.

编辑:我曾尝试使用 .length() 方法来限制输入,但这不允许大于 .length() 参数的整数。

采纳答案by Andrew_CS

Here is a working sample of how you could accomplish what you need. I broke it up so that the user is prompted once for each input which makes it easier to validate. I changed your checkInputmethod to getInputwhich only returns valid user input as a Stringwhere it is then converted into an int.

这是一个关于如何完成您需要的工作示例。我将其分解,以便为每个输入提示用户一次,这使得验证更容易。我将您的checkInput方法更改为getInput仅返回有效的用户输入作为 aString然后将其转换为int.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int inputInt = Integer.parseInt(getInput(in, "Enter an integer: "));
    int inputBase = Integer.parseInt(getInput(in, "Enter a base: "));
    System.out.println("Int: " + inputInt + ", base: " + inputBase);
}

public static String getInput(Scanner in, String prompt) { // Get valid user input
    System.out.print(prompt); // Tell user what to input
    String text = "";
    while (true) { // Keep looping until valid input is found
        text = in.nextLine(); // Get input from stdin
        if(isInteger(text)) // Check if they put in integer
            break; // Exit loop
        System.out.print("Try again, " + prompt); // Wasn't valid, prompt again
    } 
    return text; // Return valid user input
}

private static boolean isInteger(String str) { // Check if string is integer
    try {
        Integer.parseInt(str); // If this doesn't fail then it's integer
        return true;
    } catch(NumberFormatException e) {
        return false; // Wasn't integer
    }
}

Sample run:

示例运行:

Enter an integer: 2 dog five 3
Try again, Enter an integer: 2
Enter a base: cat
Try again, Enter a base: 3
Int: 2, base: 3

It helps to separate functionality - you were trying to read input, validate input, and convert to intall in one method. If you break it up it becomes easier to manage.

它有助于分离功能 - 您试图int在一种方法中读取输入、验证输入并转换为全部。如果你把它分解,它会变得更容易管理。

回答by Zach

If you want to only get the first two words (or strings delimited by spaces) you can use the str.split(" ");method. For example:

如果您只想获取前两个单词(或由空格分隔的字符串),您可以使用该str.split(" ");方法。例如:

String input = in.nextLine(); // Gets the next line the user enters (as a String)
String[] inputWords = input.split(" "); // inputWords[0] is first word, inputWords[1] 
                                        // is second word... etc
String validInput = inputWords[0] + " " + inputWords[1]; // Combines the first and 
// second words into a string, so if you had "5 five %" validInput would be "5 five"
// inputWords[0] is "5", inputWords[1] is "five", inputWords[3] is "%" etc for any other words...

This will essentially limit the number of inputs to two words.

这将从本质上将输入的数量限制为两个字。

我希望这有帮助!

回答by bumbumpaw

Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want 

findInLine(String pattern)

findInLine(字符串模式)

method of Scanner class of java.util package. This method returns a String object that satisfies the pattern specified as method argument.

的 Scanner 类的方法java.util package。此方法返回一个 String 对象,该对象满足指定为方法参数的模式。

see this article

看这篇文章

回答by joe

Scanner scan = new Scanner(System.in);

Scanner scan = new Scanner(System.in);

    System.out.println ("enter a 2 numbers");

    String s;

    s = scan.nextLine();

    Scanner scan2 = new Scanner(s);

    int one = scan2.nextInt();
    int two = scan2.nextInt();

    System.out.println (" int 1 = " + one + " int 2 = " + two);

enter a 2 numbers 23 45 68 96 45 int 1 = 23 int 2 = 45

输入 2 个数字 23 45 68 96 45 int 1 = 23 int 2 = 45

Process completed.

过程完成。