gpt4 book ai didi

java - 我如何只接受整数输入(只有扫描仪类以及 if 和 else 语句或 while 循环(如果可能 - 没有 boolean 值))?

转载 作者:行者123 更新时间:2023-11-30 08:24:19 25 4
gpt4 key购买 nike

这是我目前的代码:

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;
}

我必须使用 integer.parseInt 才能让我的其余代码正常工作,所以我无法更改它。有什么方法可以只取整数而不是字母?我的代码会产生错误,因为如果我输入一个字母,parseInt 将产生红色错误,而不是输出像“再试一次。请输入数字”之类的字符串。

最佳答案

你需要用 try catch 包围你的 parse.int像这样

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.");
}
}

关于java - 我如何只接受整数输入(只有扫描仪类以及 if 和 else 语句或 while 循环(如果可能 - 没有 boolean 值))?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23047881/

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