简体   繁体   English

你如何提示用户在java中输入

[英]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.所以我刚开始学习 Java,这就像我的第一天,我想尝试制作一个投币游戏。 I already know a decent amount of Javascript and so i was trying to apply that knowledge to java.我已经了解相当多的 Javascript,所以我试图将这些知识应用到 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.我还尝试了一些代码,您可以让用户导入一个字符串,但稍后您可以在我的程序中看到我将变量 userChoice 更改为一个数字。 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 im tottaly open to other ways of doing this: Thanks in advanced!但我完全愿意接受其他方式来做到这一点:在此先感谢! 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!")

          }


          }

    }

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 int s or enum s.最好只使用==来比较intenum的值。 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 (注意:您不能将一种类型的对象转换为另一种不相关的对象,如果您想这样做,则必须创建一个新对象):这个:

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
        }
    }

You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.您已经导入了 Scanner 类,因此您现在可以创建一个 Scanner 类型的变量来获取输入。

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

nextLine() can be used to input a character or a string from the user. nextLine()可用于从用户输入字符或字符串。

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;
      }

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:导入 java.util.Scanner 后,为了从用户那里获取字符串形式的输入,创建一个参数化 System.in 的 Scanner 对象,并为 userChoice 分配由 Scanner 对象调用的 nextLine() 的值:

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.使用string1.equals(string2)查看两个字符串是否相等。 Also, bob = (int) Math.floor(Math.random()*2);另外, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2);真的是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.因为将 double 转换为整数会将 double 截断为小于或等于它的最高整数。

"String" datatype in Java can hold both numbers and strings (as you asked). Java 中的“字符串”数据类型可以包含数字和字符串(如您所问)。 You can get user input using Scanner utility as below:您可以使用 Scanner 实用程序获取用户输入,如下所示:

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"){...} 

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM