Ray25Lee
Ray25Lee

Reputation: 65

How do I get a String input to accept a possible integer in Java?

I'm a very beginner at Java, and I'm creating a program that accepts user input in Java, and I'm trying to create a string that accepts strings or integers as responses. However, when I type in the acceptable integer, it won't recognize the answer. Here is the code:

System.out.println("How much time you you want to spend on this? Less than 30 mins, less than an hour, or more? Type \"30\", \"h\", or \"m\".");
    String ls = console.next();

    while (!ls.equalsIgnoreCase("h") && !ls.equalsIgnoreCase("m") && ls.equalsIgnoreCase("30")) {
        System.out.println("Type shit properly.");
        ls = console.next();
    }

    if (ls.equalsIgnoreCase("30")) {
        System.out.println("Do you want to do something fun? Y/N.");
        String dare = console.next();
        while (!dare.equalsIgnoreCase("y") && !dare.equalsIgnoreCase("n")) {
            System.out.println("Seriously?");
            dare = console.next();
        }
    }

Every time I type 30 into the console, it gives me my error report "Type shit properly" instead of proceeding to the "if ls equals 30" section. It works fine for the m and h options, just not the number. I thought strings accepted numbers as well; was I wrong? How do I get this to accept both Strings AND integers as input?

Upvotes: 0

Views: 89

Answers (2)

Vivek
Vivek

Reputation: 1525

use !ls.matches("30") instead of ls.equalsIgnoreCase("30")

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

Change

&&ls.equalsIgnoreCase("30")

to

&&!ls.equalsIgnoreCase("30")

or if you want to allow any number, you could use String.matches(String)

&&!ls.matches("\\d+")

Upvotes: 1

Related Questions