0

I want to check if the user inputed in a string, and if he does I want to print it out or warn him to enter a string next time. I know that my problem is with the condition in the if statement but I don't know which method I should use in this case. I use hasNextInt for Integers but from the look of it this doesn't work like I would hope with String.

EDIT: Just to clarify from the comments: the text should hold only a specific character set like a-z, A-Z and spaces.

import java.util.Scanner;

public class JavaLessonTwoTest {
    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("Enter string please: ");

        if (userInput.hasNext(String("")) {
            String stringEntered = userInput.next();
            System.out.println("You entered " + stringEntered);
        } else {
            System.out.println("Enter a string next time.");
        }
    }
}
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
  • 4
    What do you mean by "string"? String can hold any kind of input from user, how can he enter something that is not a string? – user3707125 Dec 21 '15 at 10:42
  • hasNext() with a String argument is used to check if the input confirms to a regular expression: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNext(java.lang.String) – Wim Deblauwe Dec 21 '15 at 10:43
  • 2
    I'm guessing your not allowing integers to be input by the user, as a String can contain anything. If I was you I would read the value first and then perform validation on that String to check if it containers integers or other unwanted character, as appose to the current level you are validating at. – Nathan Dec 21 '15 at 10:44
  • My use of word was wrong. Sorry for that. What I want is for the user to input a character not an integer or any number. –  Dec 21 '15 at 10:48
  • 1
    I think you have to define what do you mean "string" in your code scope. For example: "for this scope, string can hold only a-z, A-Z and spaces. Is that what you want? – Paulo Dec 21 '15 at 10:49
  • 1
    @Paulo Yes that is what I want. –  Dec 21 '15 at 10:49
  • Then Character.isLetter may do what you want! – anna Dec 21 '15 at 10:50
  • use the instanceof operator – Zia Dec 21 '15 at 10:58
  • @Zia No need for the instanceof. Scanner.next() will return a String value. – anna Dec 21 '15 at 10:59
  • we will take the vale scanner and check for the number = sc.nextInt() etc and then use the instanceof with number,same for double,long etc... – Zia Dec 21 '15 at 11:13

3 Answers3

2

What you probably are searching for, is a Regular Expression.
I'll give you an example, so you have to adapt it to your code:

public class Patt {
    public static void main(String... args) {
        String[] tests = {
        "AA A",
        "ABCDEFGH123",
        "XXXX123",
        "XYZabc",
        "123123",
        "X123",
        "123",
        };
        for (String test : tests) {
            System.out.println(test + " " + test.matches("[a-zA-Z ]*"));
        }
    }
}

The point is the regular expression

[a-zA-Z ]*

in the call test.matches("[a-zA-Z ]*"). It means "match only strings that have any number of letters which are either from a to z, A to Z or whitespace ().

Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
Paulo
  • 1,458
  • 2
  • 12
  • 26
  • 1
    Note that if you use *, it will match an empty string like "". But if it's not the case, you can use + instead of *. An asterisk can match 0 or more. A plus will match 1 or more. – Paulo Dec 21 '15 at 11:04
  • 1
    I will make sure to check your way too. I am still learning the basics of java, and knowing different ways to solve one task is going be useful. –  Dec 21 '15 at 11:27
2

A console is a text interface, thus a user can only input data as String. Given that, you can try to parse the input to an Integer, Float, Book or any other type depending on your needs.

What you are trying to do is probably something like this:

while(true) {
    System.out.print("Enter string please: ");

    String input = userInput.next();

    boolean isInputInt;
    try {
        int number = Integer.parseInt(input);
        // parsing to int succeeded
        isInputInt = true;
    } catch (NumberFormatException ex) {
        // parsing to int failed
        isInputInt = false;
    }

    if (isInputInt) {
        System.out.println("Integers are not allowed.");
        // retry
        continue;
    } else {
        System.out.println("You entered " + input);
        // proceed
        break;
    }
}
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
  • This work, but there was one part I didn't understand. What does NumberFormatException ex do? –  Dec 21 '15 at 11:21
  • The call to ``Integer.parseInt(input)`` will ``throw`` a ``NumberFormatException`` if it fails. Which is exactly the case if ``input`` does not represent a valid integer. You can use the exception in the ``catch`` clause to get gain some details about the failure, e.g. error message and the stack trace. I suggest reading about [Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/) online.... – Binkan Salaryman Dec 21 '15 at 11:26
0

According to this: Restrict string input from user

This should work:

public static void main(String[] args) throws ParseException {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter String only with letters:");
    while (!sc.hasNext("[A-Za-z]+")) {
        System.out.println("Digits are not allowed");
        sc.next();
    }
    String word = sc.next();
    System.out.println("User input was : " + word);
}
Community
  • 1
  • 1
i23
  • 508
  • 2
  • 12
  • 1
    This is a code-only answer, which is discouraged on SO. You can improve it by explaining how it solves the OP's question. For further guidance you can read [answer]. – Software Engineer Dec 21 '15 at 11:01