我正在尝试按照用户指示的高度建造金字塔。如果我使用下面的代码,它将告诉我我没有引入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
}
您遇到的问题是该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] 删除。
我来说两句