hasNextInt实际如何工作?(java)

Pablito

我正在尝试按照用户指示的高度建造金字塔。如果我使用下面的代码,它将告诉我我没有引入Integer btw 1-20 ...注释if(scan.hasNextInt ...)使代码正常工作,只要我不插入数字<1。

是否正确使用hasNextInt()

Scanner scan = new Scanner (System.in);
int rows = 0, i=1, j=0;

    //Asking for the Input
System.out.println("How many rows should the pyramid have?\n"+
                    "(Insert an Integer btw 1-20)");

    //Checking if there's an Input
if (scan.hasNextInt() && rows>0 && rows<=20)
    rows = scan.nextInt();
else System.out.println("Not an Integer btw 1-20 inserted");

    //Building the pyramid
while (i<=rows){
    while (j<i){System.out.print("*");j++;}
    System.out.println();
    i++;j=0;
}

scan.close(); //closing scan
}
弗朗西斯科·罗梅罗(Francisco Romero)

您遇到的问题是该rows变量等于变量,0因此不会输入该if语句。

if (scan.hasNextInt() && rows>0 && rows<=20) //Here rows it's equals to 0
    rows = scan.nextInt();
else System.out.println("Not an Integer btw 1-20 inserted");

您必须先修改rows变量,然后再输入if,否则,它将始终显示消息"Not an Integer btw 1-20 inserted"


尝试做:

if (scan.hasNextInt())

    do{
       rows = scan.nextInt();
    while(rows>0 && rows<=20);

else System.out.println("There is no integer");

如果您希望用户强制int在这两个数字之间输入如果没有,则可以用语句替换do-while循环if

希望对您有帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章