Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何仅获取整数输入(仅使用scanner类和if and else语句,或者如果可能,使用while循环-无布尔)?_Java_Loops_Integer - Fatal编程技术网

Java 如何仅获取整数输入(仅使用scanner类和if and else语句,或者如果可能,使用while循环-无布尔)?

Java 如何仅获取整数输入(仅使用scanner类和if and else语句,或者如果可能,使用while循环-无布尔)?,java,loops,integer,Java,Loops,Integer,以下是我目前掌握的代码: import java.util.Scanner; public class Whatever{ public static void main(String[] args) { Scanner keyboard = new Scanner (System.in); System.out.println("How many pigs are there?"); int number = Integer.parseInt( keyboard

以下是我目前掌握的代码:

import java.util.Scanner;
public class Whatever{
    public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("How many pigs are there?");
    int number = Integer.parseInt( keyboard.nextLine() );
    int continueProgram = 0
    while(continueProgram == 0)
        {
            if (number>= 0 && number <= 32767)
            { do this;
                      continueProgram++;
            }else{
                     do this;
            }
import java.util.Scanner;
公务舱{
公共静态void main(字符串[]args){
扫描仪键盘=新扫描仪(System.in);
System.out.println(“有多少头猪?”);
int number=Integer.parseInt(keyboard.nextLine());
int continueProgram=0
while(continueProgram==0)
{

如果(number>=0&&number,则需要使用类似的

int number = 0; // you need to initialize your variable first
while (true) {
    try {
    number = Integer.parseInt(keyboard.nextLine());
    break; // this will escape the while loop
    } catch (Exception e) {
    System.out.println("That is not a number. Try again.");
    }
}
试试这个:

 Scanner keyboard = new Scanner (System.in);
 System.out.println("How many pigs are there?");
 if(keyboard.hasNextInt()) {

   int number =  keyboard.nextInt();        

   }else{ 
        System.out.println("Not an integer number!");
        keyboard.next();
   }

您的程序如何说“再试一次。请输入数字”或者类似的东西。
当你从未试图告诉它这样做时?因为parseInt停止代码的其余部分,让我将字符串放入其中进行输出。嗯,实际上我的问题是:如果我输入一个字母,程序使用system.out.println方法转到catch方法,我如何将其循环回“有多少头猪?”从我的代码中删除?@user3503794我为您更新了上面的代码,只需复制并粘贴即可。哇,太快了。谢谢codecamp。我会试试看。@user3503794还有错误吗?此代码将按照您的要求循环。没有错误。我投票支持您。非常感谢。哦,好的。让我试试看。谢谢您的输入。如果您想循环然后就像第一个答案一样使用while循环,注意输入语句仅在数字为整数时有效,因此,我想这就是您要寻找的。谢谢您的帮助。下次我会记住这一点