简体   繁体   English

如何使用带整数的java.util.Scanner

[英]How do I use java.util.Scanner with integers

I just started learning java and I want to make a simple program where it requests the persons name, outputs the name then asks for the thier favorite number. 我刚刚开始学习Java,我想编写一个简单的程序,在该程序中要求输入人名,然后输出姓名,然后要求输入自己喜欢的号码。 It will then compare their number to the number 6 and will output something depending on if the number is larger or smaller than 6. 然后,它将数字与数字6进行比较,并根据数字是大于还是小于6输出一些信息。

I am getting a "String to int convert" error in Netbeans which has to do with the scanner. 我在Netbeans中收到“与String进行int转换”错误,该错误与扫描仪有关。 Hopefully I am asking this correctly but how can I make the scanner pick-up integers? 希望我能正确地问这个问题,但是我怎样才能使扫描仪拾取整数? Thanks 谢谢

package javaapplication2;
import java.util.Scanner;
import java.lang.String;

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

        // Creating an instance of the scanner class.
        // Gets name and numbers.
        Scanner getName = new Scanner(System.in);
        Scanner getNumber = new Scanner(System.in);

        //Holds name and number
        String userName;
        int userNumber;

        // Asks for the users name.
        // Holds name in userName.
        System.out.println("What is your name?");
        userName = getName.nextLine();

        //Reponds with the users name.
        System.out.println("Hello" + userName + "!");

        //Asks for favorite number.
        // Holds number in userNumber.
        System.out.println("What is your favorite number?");
        userNumber = getNumber.nextLine();

        // Checks if users number is larger than 6.
        if (userNumber > 6) {
            // Stuff goes here.
        }       
    }

}

You should use only one Scanner for one input stream: 您应仅对一个输入流使用一个Scanner

Scanner in = new Scanner(System.in);

And after that you should use it's methods to get integers: 之后,您应该使用它的方法来获取整数:

String name = in.nextLine();
int number = in.nextInt();

To be sure, you should read the documentation for Scanner : 可以肯定的是,您应该阅读Scanner的文档:

  1. Scanner 扫描器
  2. Scanner::nextLine 扫描仪:: nextLine
  3. Scanner::nextInt 扫描仪:: nextInt

这可能会有所帮助: Scanner的Javadoc页面

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

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