如何在Java中验证输入是否为正整数
我正在尝试创建一个输入,以验证输入是否为整数,是否为正。现在我有这个。如何检查整数是否为正 编辑:我还需要它一直询问,直到你输入一个正整数如何在Java中验证输入是否为正整数,java,Java,我正在尝试创建一个输入,以验证输入是否为整数,是否为正。现在我有这个。如何检查整数是否为正 编辑:我还需要它一直询问,直到你输入一个正整数 /** * pre: none * post: returns a positive integer as entered by the user */ public static int getInput(){ int a; Scanner scan = new Scanner(System.in); Syst
/**
* pre: none
* post: returns a positive integer as entered by the user
*/
public static int getInput(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
while (!scan.hasNextInt()){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
scan.next();
}
a = scan.nextInt(); //Assigns entered integer to a
return a; //replace with correct code
}
简单:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
旁注:
选中
返回参数的signum函数;如果参数为
零,如果参数大于零,则为1.0;如果参数大于零,则为-1.0
小于零
您可以在单个循环中执行此操作,类似于跳过无效输入的循环。但是,由于循环需要确保两件事(即输入一个数字,该数字为正数),因此需要修改其主体 由于输入至少需要执行一次,因此
do
/while
循环是更好的选择
从满足所需条件的循环开始,即“我得到一个数字,该数字为正”:
就是这样-现在有了一个循环体,可以为您读取值,还有一个循环条件,可以确保值在退出时为正值。将循环与循环体组合,然后进行尝试。它应该可以做到这一点。您可以尝试以下方法:
public static int getInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
int a = scan.nextInt();
while (a < 0){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
a = scan.nextInt();
}
return a;
}
publicstaticintgetinput(){
扫描仪扫描=新扫描仪(System.in);
System.out.println(“输入所需数量”);
int a=scan.nextInt();
而(a<0){//检查输入是否为整数
System.out.println(“输入正整数”);
a=scan.nextInt();
}
返回a;
}
从数学上讲,您将如何检查此问题?低质量问题。。。。应该搜索google
How i make this的第一个可能的副本,这样它会一直请求输入,直到结果为正integer@Tolkingdom:-把它放在一个do..while循环中!如果我输入一个字母而不是一个数字,则在测试此代码时会使程序崩溃;如果我输入一个数字,如-20,则不会显示“我需要一个整数,请重试”。因为-20是一个有效的整数。@Specializet您可以添加一个无条件提示。有一种方法请参见编辑。是的,但我只需要正整数谢谢你的帮助,这就是我需要的。
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scan.nextLine();
}
public static int getInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
int a = scan.nextInt();
while (a < 0){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
a = scan.nextInt();
}
return a;
}