0

I am taking input from user and it should be string only, but code is not working as I expected. Here is my code `

while(true){
    try{
      System.out.print("Enter test string");
      str=sc.nextLine();
      break;
    }
    catch(InputMismatchException e) {
     System.out.println("Please enter String value");
     continue;
    }
  }
  System.out.println(str);
`

If I am giving integer value than it should ask again but here it is printing integer value.Also no Special character

  • 4
    A `String` can contain ascii characters that are digits... why would "123" be illegal? – Elliott Frisch Jun 12 '18 at 18:32
  • try with this `str = sc.nextLine(); if (str.matches("\\d")) { continue; } break;` – Youcef LAIDANI Jun 12 '18 at 18:34
  • The code you provided does never throw an `InputMismatchException`. – Turing85 Jun 12 '18 at 18:35
  • `[teach-me]` When the user types *12345*, it's a string. It can also be interpreted as integer, floating point value, hex integer and possibly in other ways, but first and foremost it's a string. –  Jun 12 '18 at 18:52

4 Answers4

1

If you tried to parse the integer directly, then you'd get a more meaningful exception to catch.

String str = "";
Scanner sc = new Scanner(System.in);
while (true) {
    try {
        System.out.print("Enter test string");
        str = sc.nextLine();
        Integer.parseInt(str);
        System.out.println("Please enter String value");
    } catch (NumberFormatException e) {
        // You *didn't* get a number; you actually have a String now.
        // You can terminate the loop here.
        break;
    }
}
System.out.println(str);
Makoto
  • 104,088
  • 27
  • 192
  • 230
0

check if string not number like this:

while(true){
        try{
            System.out.print("Enter test string");
            str=sc.nextLine();

            if(isNumeric(str)) {
                continue;
            }
            break;
        }
        catch(InputMismatchException e) {
            System.out.println("Please enter String value");
            continue;
        }
    }
    System.out.println(str);
}

public static boolean isNumeric(String str)
{
    for (char c : str.toCharArray())
    {
        if (!Character.isDigit(c)) return false;
    }
    return true;
}
mohsenJsh
  • 2,048
  • 3
  • 25
  • 49
0

If you are only trying to check if the string is NOT a number, you can try

String str = sc.nextLine();
if (StringUtils.isNumeric(str))
    System.out.println(str);

but this method will not work if your number has a decimal or something.

check How to check if a String is numeric in Java

for a similar answer

Jiahao Zhao
  • 101
  • 8
-1
str=sc.nextLine();

takes everything as a string hence there is no exception. Try using statement like this

int num; 
  &
num=sc.nextInt();

and you will find that the exception will is caught so there is no problem with the code.

Suppose that user will enter "This is 1 String" even though it contains integer but still it is a String. Same applies every time even when user enter "43728" it is still considered a String

here is how you can accomplish your goal

while(true){
              System.out.print("Enter test string");
              str=sc.nextLine();
              Pattern pattern = Pattern.compile("\\d");
              Matcher matcher = pattern.matcher(str);
              if (matcher.find()) {
                  //System.out.println(matcher.group(0));
                 continue; 
              }
              break;
          }
Sundeep
  • 452
  • 2
  • 12
  • Consider not using the name "str" for a variable that is meant to be an int. That is just lying to the reader. – GhostCat Jun 12 '18 at 18:56
  • i tried not to change the syntax for the convenience of questioner. if stackoverflow thinks its bad i'll edit it and never do again – Sundeep Jun 12 '18 at 19:00
  • We all have opinions about code conventions, and they're just that: opinions. You should write the clearest code you can. – Makoto Jun 12 '18 at 19:04
  • That said, one irrefutable *fact* is that using `nextInt` is *not* going to give the OP what they want. They need to consume the entire line at once, even if this means that they're going to have a string with "d1234" (which would qualify as a "String"). – Makoto Jun 12 '18 at 19:05
  • I understand it will not solve his problem. Here i was only trying to tell him that there is no problem with code the problem is in Logic of code – Sundeep Jun 12 '18 at 19:08