1

I´m having a question about my program. I´m trying to figure out, how i can check if the s.nextLine() input form a user is only holding ints form 1 to 49 in it or also letters. I know that the "eingabe" is a string so I can’t just use an if right?

My problem is, that I´m relative new in programming with java and i have no idea for a solution. :/ Maybe you can help me that would be great!

    public static int Scanner() {
        Scanner s = new Scanner(System.in);
        String eingabe = s.nextLine();

        //???

        return eingabe;
    }
melpomene
  • 84,125
  • 8
  • 85
  • 148
IceCube
  • 13
  • 2
  • 2
    (Welcome to SO!)(`Scanner.nextLine()` returns a `String` with no subsequent relation. You can use any "String function", but have a look at [Java's regular expressions](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html).) – greybeard Nov 19 '17 at 12:32

1 Answers1

1
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class MyClass {
    public static void main (String[] args) {
       try {
                int x = Scanner();
                if(x >= 1 && x <= 49) {
                    System.out.println("Yes");
                }
                else {
                    System.out.println("No");
                }
        }
        catch(java.lang.NumberFormatException e) {
            System.out.println(e);
        }
        //Second Method Using Regex.
        try {
            int x = useRegex();
                if(x >= 1 && x <= 49) {
                    System.out.println("Yes");
                }
                else {
                    System.out.println("No");
                }
        } catch(java.lang.NumberFormatException e) {

            System.out.println(e);
        }
    }
    public static int Scanner() {
        Scanner s = new Scanner(System.in);
        String eingabe = s.nextLine();
        return Integer.parseInt(eingabe);
    }

    public static int useRegex() {
        Scanner s2 = new Scanner(System.in);
        String eingabe = s2.nextLine();
        Pattern p = Pattern.compile("^[\\+-]?\\d+$");
        Matcher m = p.matcher(eingabe);
        boolean b = m.matches();
        if(b) {
            return Integer.parseInt(eingabe);
        }

        else {
            throw new java.lang.NumberFormatException();
        }
    }

}  

Here I am using try catch block to handle if the input format is wrong. If it is wrong then the Exception

java.lang.NumberFormatException

will occur and then if it is a valid number then I am checking whether it is between 1 and 49. Integer.parseInt(num) is used to convert a String into number. https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String). Try catch is used to handle to exceptions without . See here

By using regex also I have mentioned. See this for regex

Brij Raj Kishore
  • 1,595
  • 1
  • 11
  • 24