0

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?

2 Answers 2

1

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+")
Sign up to request clarification or add additional context in comments.

2 Comments

facepalm Thank you very much. Human error. One of the dumbest things I've done all day. (Thanks for answering.) Cheers.
Interesting; I didn't know about the allowing any number code; that'll definitely be useful, later on.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.