6

I am trying to get my code to prevent a user input from having a number in it.

Essentially I want the code to do as follows:

  1. ask for input
  2. receive input
  3. test whether or not the input contains a number(ex: 5matt vs matt)
  4. if contains a number I want to System.out.println("Error: please do not input a number");

Heres the kicker (and why it's not a duplicate question): I can't use loops or other statements we haven't learned yet. So far the only true statements we've learned are if/else/else if statements. That means I can not use for loops, like some of the answers are suggesting. While they're great answers, and work, I'll lose points for using them.

System.out.println("Please input the first name: ");    
String name1 = in.next();
System.out.println("Please input the second name: ");
String name2 = in.next();
System.out.println("Please input the third name: ");
String name3 = in.next();

name1 = name1.substring(0,1).toUpperCase() + name1.substring(1).toLowerCase();
name2 = name2.substring(0,1).toUpperCase() + name2.substring(1).toLowerCase();
name3 = name3.substring(0,1).toUpperCase() + name3.substring(1).toLowerCase();

I have this already but I can't figure out how to test if the input only contains letters.

The SE I loved is dead
  • 1,517
  • 4
  • 23
  • 27
matt kaminski
  • 75
  • 1
  • 5
  • 4
    You should get used to reading through the [API documentation](http://docs.oracle.com/javase/8/docs/api/index.html). Specifically, `Character` has an `isDigit()` method. – azurefrog Sep 14 '16 at 22:39
  • **Or**, use a *regular expression* like `str.matches(".*\\d.*")` (where `str` is a `String`), which will tell you **if** the `String` contains any digits. – Elliott Frisch Sep 14 '16 at 22:39
  • `if(name1.matches(".*\\d+.*") || name2.matches(".*\\d+.*") || name3.matches(".*\\d+.*")){ // stuff here; } else { //no nums; }` – px06 Sep 14 '16 at 22:40
  • [Use Scanner to accept only valid int](http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input#2913026), but invert the condition – OneCricketeer Sep 14 '16 at 22:40
  • @cricket_007 i misclicked and retraced it 10 seconds after clicking... =] – nhouser9 Sep 14 '16 at 22:41
  • 3
    Possible duplicate of [Check if a String contains numbers Java](http://stackoverflow.com/questions/18590901/check-if-a-string-contains-numbers-java) – Jose Ignacio Acin Pozo Sep 14 '16 at 22:42
  • 1
    *"Small rant: this wouldn't be so hard if my professor actually taught us a way to do this."* - Well I think your professor is doing you a big favor here. In the real world of programming, you will often encounter small (and big) programming problems that nobody has taught you how to solve. One of the things programmers need to learn is how to solve these problems for themselves. – Stephen C Sep 14 '16 at 22:48
  • Have you learned exceptions? Just try to parse the integer and capture the exception if it fails. For a small hw assignment I wouldn't be surprised if this is what the teacher is looking for. Unfortunately the right answer and the acceptable answer don't usually match up while you're still in school. – Mike McMahon Sep 15 '16 at 21:52
  • @mattkaminski If an user answered your question please also **accept** his answer ([Accepting Answers: How does it work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)). If not than please specify what remains unanswered, this is a really crucial part of StackOverflow, thank you very much. – Zabuzard Jul 27 '17 at 12:07

4 Answers4

3

Okay, there are many ways to deal with this. A good thing would be to use Regex (text matching stuff). But it seems that you should only use very basic comparison methods. So, let's do something very basic and easy to understand: We iterate over every character of the input and check whether it's a digit or not.

String input = ...
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
    char c = s.charAt(i);

    // Check whether c is a digit
    if (Character.isDigit(c)) {
        System.out.println("Do not use digits!");
    }
}

This code is very straightforward. But it will continue checking even if a digit was found. You can prevent this using a helper-method and then returning from it:

public boolean containsDigit(String text) {
    // Iterate over every character
    for (int i = 0; i < input.length(); i++) {
        char c = s.charAt(i);

        // Check whether c is a digit
        if (Character.isDigit(c)) {
            return true;
        }
    }
    // Iterated through the text, no digit found
    return false;
}

And in your main program you call it this way:

String input = ...
if (containsDigit(input)) {
   System.out.println("Do not use digits!");
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • At least use a for-each loop. – GhostCat Sep 14 '16 at 22:42
  • At least `break` on the first digit – OneCricketeer Sep 14 '16 at 22:42
  • 1
    At first I wanted but then I thought of OP maybe not knowing such stuff as it seems that he is a beginner. – Zabuzard Sep 14 '16 at 22:43
  • Yes, but even a beginner might enjoy typing `for (Character c : input...) instead of the for int counter thingy. – GhostCat Sep 14 '16 at 22:44
  • Edited for `break`. – Zabuzard Sep 14 '16 at 22:46
  • 1
    `containsDigit` needs a `return false` at the end. – nanofarad Sep 14 '16 at 22:52
  • should have included this in my original post but i can't use for loops. since we haven't learned them yet, they'll take off points for using them. – matt kaminski Sep 15 '16 at 16:47
  • Every approach which you can find on earth will need to iterate through the text with a `loop`. If you find a magic method which does the job, internally it will also iterate with a `loop`. Such a magic method would be inside the answer of @Silverstorm : `str.matches(".*\\d.*")`. This returns `true` if the text matches the given `pattern`. The pattern, which is **Regex**, means `anything, then a digit, then anything`. – Zabuzard Sep 15 '16 at 17:44
2

Use a regular expression to filter the input

Eg

str.matches(".*\\d.*")

See this link for more info

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Silverstorm
  • 15,398
  • 2
  • 38
  • 52
0

There are several ways you could do this, among others:

  • Iterate over all the chars in the string and check whether any of them is a digit.
  • Check whether the string contains the number 1, number 2, number 3, etc.
  • Use a regular expression to check if the string contains a digit.

(Java Regular Expressions)

Martin
  • 1,130
  • 10
  • 14
0

If you're allowed to define functions, you can essentially use recursion to act as a loop. Probably not what your prof is going for, but you could be just inside the requirements depending on how they're worded.

public static boolean stringHasDigit(String s) {
    if (s == null) return false; //null contains no chars
    else return stringHasDigit(s, 0);
}

private static boolean stringHasDigit(String s, int index) {
    if (index >= s.length()) return false; //reached end of string without finding digit
    else if (Character.isDigit(s.charAt(index))) return true; //Found digit
    else return stringHasDigit(s, index+1);
}

Only uses if/elseif/else, Character.isDigit, and String.charAt, but recursion might be off limits as well.

Mshnik
  • 7,032
  • 1
  • 25
  • 38