简体   繁体   English

为什么我的扫描仪要求两次输入?

[英]Why is my Scanner asking for an input twice?

I am writing code for a program I am creating, and all I want this part of my code to do is ask the user to input a number. 我正在为要创建的程序编写代码,而我希望代码的这一部分要做的就是要求用户输入数字。

import java.util.Scanner;

public class DiceRoller {       


    System.out.println("Please input a number of you choice"); 

    Scanner x = new Scanner(System.in);

    double repeats = x.nextInt(); 

    if(x.hasNextInt()){            
        repeats = (int)Math.round(repeats);


    }          

}

So this asks me for a number, but I will have to input twice. 所以这要求我输入一个数字,但是我将不得不输入两次。

It also only uses the first input as the variable 它还仅将第一个输入用作变量

After you got a nextInt() , you asked it if it had another input with hasNextInt() it only knows this if you enter something more. 获得nextInt() ,您询问它是否具有另一个具有hasNextInt()输入,只有输入更多内容,它才知道这一点。

Perhaps you intended to put nextInt() inside the if block. 也许您打算将nextInt()放在if块内。 Perhaps you also want to use int repeats as its an int value. 也许您还想使用int repeats作为其int值。

You are calling x.hasNextInt() and the Scanner waits for another input to check if it is an int. 您正在调用x.hasNextInt() ,并且扫描程序等待另一个输入来检查它是否为int。 You are also reading in an int and assigning it to a double (which an int is not). 您还正在读取一个int并将其分配给double(一个int不是)。 And to further it, you pass your int/double hybrid to Math.round which converts it to a Long and then casts it to an int and tries to assign it to a double. 然后,将int / double混合传递给Math.round,将其转换为Long,然后将其转换为int并尝试将其分配为double。

If you are wanting to check if an a line is an int, you should try something like: 如果要检查行是否为整数,则应尝试以下操作:

System.out.println("Please enter an integer.");
String line = x.nextLine();
int res=0;
try{
   res=Integer.parseInt(line);
}catch(Exception e){
   System.out.println("Not a number");
}

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

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