3
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".

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

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?

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

user2453911
  • 57
  • 1
  • 2
  • 9
  • What do you want to limit off of? String length, words, etc.? – Andrew_CS Jul 19 '14 at 00:19
  • I want the user to input 2 integers, say 5 2. The Scanner input reads spaces as a delimiter. But if the user inputs more than 2 inputs, say 5 2 8 9, I only want the Scanner method to take in the first 2 values. – user2453911 Jul 19 '14 at 03:25

4 Answers4

3

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 checkInput method to getInput which only returns valid user input as a String where it is then converted into an 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 int all in one method. If you break it up it becomes easier to manage.

Andrew_CS
  • 2,384
  • 1
  • 14
  • 34
2
Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want 

findInLine(String pattern)

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

see this article

bumbumpaw
  • 2,338
  • 1
  • 16
  • 49
1

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

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.

I hope this helps!
Zach
  • 4,304
  • 15
  • 20
  • I think u should edit your answer cuz it seems the op wants the input to be length 5 – Kick Buttowski Jul 19 '14 at 00:41
  • This seems like it could work. I will give it a shot. – user2453911 Jul 19 '14 at 03:27
  • This is what I was looking for, thank you. FYI, if you input only 1 value it breaks but I guess I can catch that error. – user2453911 Jul 19 '14 at 04:13
  • @user2453911 Be warry though - this doesn't check anywhere to see if the input was an integer which seemed to be part of your "checking for valid input" requirement. – Andrew_CS Jul 19 '14 at 04:16
  • That is true. But it was the first(joe's worked as well) to limit it to 2 inputs. Though it seems it is not possible to limit the Scanner input when reading in the value as int. – user2453911 Jul 19 '14 at 04:18
  • @user2453911 I recommended in my answer to break it up into two separate input reads - makes the error checking/validation simpler. – Andrew_CS Jul 19 '14 at 04:19
  • @Andrew_CS but even when you input more values in one line it overloads it. Look at my comment of the output. I did give it +1(not sure if that does anything) because of the thoroughness of the answer. – user2453911 Jul 19 '14 at 04:22
  • @user2453911 I saw your comment and replied - read my comment - it was a copy and paste error. – Andrew_CS Jul 19 '14 at 04:23
1

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

Process completed.

joe
  • 29
  • 5