0

I am pretty new to Java and I was stuck when I was trying to check if the user input is texts (strings) and not numbers. hasNext(), next(), nextLine() doesn't necessarily check for strings, so I am not sure how it can be done.

import java.util.Scanner;
    public class CalculateOne {
        public static void main(String[] args) {
            System.out.print("Enter a or b");
            Scanner scan = new Scanner(System.in);
            boolean isItString = scan.hasNextLine();
        while (! isItString) {
            System.out.print("Invalid Input! \n");
            scan.next();
        }
        String type = scan.nextLine();
        System.out.println("you chose "+type);
    }

}
Bian Lee
  • 1
  • 2

2 Answers2

1

What you need to use is the hasNext(String) or hasNext(Pattern) method. These test if the next token (using the current delimiter setting) matches a regex. There are corresponding next methods for consuming the token.

The details are in the javadocs for Scanner.

So the only thing left for you to do is to "implement" the regex to match your "not a number" tokens.


You could also just call next() to get the next token and test it for "not a number". But that is going to consume the token.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Take your input as string and check whether input is number or a string.

static boolean isNumber(String s) 
        { 
            for (int i = 0; i < s.length(); i++) 
            if (Character.isDigit(s.charAt(i))  
                == false) 
                return false; 

            return true; 
        } 
Tanu Garg
  • 3,007
  • 4
  • 21
  • 29