gpt4 book ai didi

java - hasNextInt 实际上是如何工作的? (java)

转载 作者:行者123 更新时间:2023-12-01 18:12:00 24 4
gpt4 key购买 nike

我正在尝试 build 一个与用户指示的高度相同的金字塔。如果我使用下面的代码,它会告诉我我没有引入整数 btw 1-20...只要我不插入数字 < 1,注释 if (scan.hasNextInt...) 就可以使代码正常工作。

我是否正确使用了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");

在进入if之前,你必须修改rows变量,否则,它总是会显示消息“Not an Integer btw 1-20插入“

<小时/>

尝试这样做:

if (scan.hasNextInt())

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

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

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

希望对你有帮助!

关于java - hasNextInt 实际上是如何工作的? (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com