Jump to content

Scanner character check help

- - - - -

  • Please log in to reply
2 replies to this topic

#1
p03p

p03p

    Newbie

  • Members
  • PipPip
  • 12 posts
Currently i have an assignment and a part of it is to check the userinput if its a number or letter. It may only start with a letter and can only contain letters/numbers(except first char). I was given the following codes:


        private boolean nextCharIsDigit(Scanner in) {

		return in.hasNext("[0-9]");

	}


	private char nextChar(Scanner in) {

		return in.next().charAt(0);

	}

	

	private boolean nextCharIsLetter(Scanner in) {

		return in.hasNext("[a-zA-Z]");

	}

	

	private boolean nextCharIs(Scanner in, char c) {

		return in.hasNext(Pattern.quote(c+""));

	}


What im doing is:


Scanner in = new Scanner (System.in);

if(nextCharIsLetter(in)) {

    do something

}


The problem im getting is that it only works when the input is 1 letter. So it will work if i input "a" or "g" but as soon there are more characters it goes into the "else". How can i check if the first position is a letter and the following positions a number or letter.

#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
I don't know if it's exactly what you were looking for but I hope it'll help.
Also, I didn't run it since I wrote it in the browser, so it may contain errors :D

//returns true if the input String starts with a letter and contains only letters and digits, false otherwise
private boolean checkInput(String input){
    if(input==null)
        return false;

    int length=input.length();

    if(length==0)
        return false;

    if(!Character.isLetter(input.charAt(0)))
        return false;

    for(int i=0;i<length;i++){
        if(!Character.isLetterOrDigit(input.charAt(i)))
            return false;
    }

    return true;

}


#3
p03p

p03p

    Newbie

  • Members
  • PipPip
  • 12 posts
Thansk for the help i got it to work




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users