Bob Mc Muffins.
Bob Mc Muffins.

Reputation: 37

How do you prompt a user for an input in java

So I just started learning Java, its literally like my 1st day and I wanted to try to make a coinflip game. I already know a decent amount of JavaScript and so i was trying to apply that knowledge to Java. So everything has been working so far except one thing: Prompting a user for a choice.

So read online that i have to import a scanner so i did that as you can see from my code. I also tried some code where you can have the user import a string but you can see a bit later in my program I change the variable userChoice into a number. So basically I just need help with this.

If there is some way to have a variable type that can store both numbers or strings that would be best. But I'm totally open to other ways of doing this!

Here is the code:

package test;
import java.util.Scanner;

public class testclass {
    
  public static void main(String[] args) {

    // TODO Auto-generated method stub
    System.out.println("hi");
    int bob;
    bob = (int) Math.floor(Math.random()*2);
    System.out.println(bob);
            
    System.out.println("Enter heads or tails?");
    System.out.println("You entered "+ userChoice);
              
    if (bob == 0) {
      System.out.println("Computer flipped heads"); 
    } else {
      System.out.println("Computer flipped tails");
    }
              
    if(userChoice == "Heads") {
      userChoice = 0;
    } else {
      userChoice = 1;
    }
              
    if (userChoice == bob) {
       System.out.println("You win!");
    } else {
       System.out.println("Sorry you lost!")
    }
              
  }
}

Upvotes: 2

Views: 30371

Answers (5)

Hanzallah Afgan
Hanzallah Afgan

Reputation: 734

It might help you to get the ideas.

public static void main(String[] args) {
    Random rd = new Random();
    //Enter 1 0R 0
    int bob = rd.nextInt(2);
    String userChoice;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter a number");
    userChoice = sc.nextLine();
    System.out.println("You entered " + userChoice + " and bob is " + bob);
    int uc = Integer.parseInt(userChoice);
    if (uc == bob) {
        System.out.println("Hehe");
    } else {
        System.out.println("Sorry");
    }
}

Upvotes: 0

CoderMusgrove
CoderMusgrove

Reputation: 614

Use a scanner, as you said:

Scanner in = new Scanner(System.in);

Then, prompt the user to enter something in:

String userChoice = in.nextLine();

Also, when you compared strings:

if(userChoice == "Heads") {...

that's bad to do for none-primitive objects. It's best to only use the == to compare values that are ints or enums. If you compare a String like this, it won't work, because it's checking if the objects are the same. Instead, compare like this:

if(userChoice.equals("Heads")) {...

Also, to convert to an int (NOTE: You can't convert one type of object to another that aren't related in any way! You'll have to create a new object if you're wanting to do that), do this:

int myInt = Integer.parseInt(myString); // NOTE: Can throw NumberFormatException if non-number character is found.

So your program should look somewhat like:

    package test;
    import java.util.Scanner;

    public class testclass {

        public static void main(String[] args) {
            //System.out.println("hi");
            Scanner in = new Scanner(System.in);
            int bob;
            int userChoice;
            String input;
            bob = (int) Math.floor(Math.random()*2);
            System.out.println(bob);

            System.out.println("Enter heads or tails?");
            input = in.nextLine(); // waits for user to press enter.
            System.out.println("You entered "+ input);

            if (bob == 0) {
                System.out.println("Computer flipped heads"); 
            }

            else {
                System.out.println("Computer flipped tails");
            }

            if(input.equals("Heads")) {
                userChoice = 0;
            }
            else {
                userChoice = 1;
            }

            if (userChoice == bob) {
                System.out.println("You win!");
            }
            else {
                System.out.println("Sorry you lost!");
            }

            in.close(); // IMPORTANT to prevent memory leaks
        }
    }

Upvotes: 2

Efe Esenwa
Efe Esenwa

Reputation: 40

Having imported java.util.Scanner, to get input from the user as a String, create a Scanner object that parameterizes System.in and assign userChoice the value of nextLine() invoked by the Scanner object:

Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();

A few things about your code. The relational operator, ==, is used for comparing primitive data - not objects. Use string1.equals(string2) to see if two strings are equal. Also, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2); because casting a double as an integer truncates the double to the highest integer less than or equal to it.

Upvotes: 0

pvs
pvs

Reputation: 1

"String" datatype in Java can hold both numbers and strings (as you asked). You can get user input using Scanner utility as below:

Scanner input = new Scanner();
userChoice = input.nextLine(); // if it is a string 
//userChoice = input.nextInt(); // if it's integer choice 

If your string is an integer then you can also parse it to get its integer value. For parsing:

int value = Integer.parseInt(userChoice);

Also for comparing String values you should use "equals" function rather than "==".

if(userChoice.equals("Heads")){...} //rather than if(userChoice == "Heads"){...} 

Upvotes: 0

Jash Jacob
Jash Jacob

Reputation: 580

You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.

 Scanner in = new Scanner();
 userChoice = in.nextLine();

nextLine() can be used to input a character or a string from the user.

To convert the string into a integer, You can assign the integer value to the string in the following way.

   if(userChoice == "Heads") {
             userChoice = "" + 0;
          }
      else {
             userChoice = "" + 1;
      }

Upvotes: 0

Related Questions