java判断是否失效_java – 如何在输入有效之前检查无效输入和循环?

我试图从用户输入中找到列表中的最小数字.我需要询问用户列表中将包含多少个数字(并且只接受正数而不是字母),然后询问他们列表中的数字是什么(仅接受数字).如何检查并保持循环直到数字有效?

public class SmallestInt {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

// Initialize a Scanner to read input from the command line

Scanner input = new Scanner(System. in );

int totalIntegers = 1;

int num = 0;

int smallest = 0;

boolean inputValid = false;

/* Prompt the user and validate their input to ensure they've entered a positive (greater than zero) integer. Discard/ignore any other data.

*/

while (!inputValid)

{

System.out.print("How many integers shall we compare? (Enter a positive integer): ");

try {

totalIntegers = input.nextInt();

inputValid = true;

} catch (NumberFormatException e) {

System.out.println("Invalid input!");

}

/* Read in the candidates for smallest integer

* Validate this input as well, this time ensuring that the user has provided a valid int (any int will do at this point) and discarding any other data

*/

for (int ii = 1; ii <= totalIntegers; ii++) {

// Prompt

System.out.print("Enter value " + ii + ": ");

num = input.nextInt();

if (ii == 1) smallest = num;

else if (num < smallest) smallest = num;

}

// display smallest int

System.out.println("The smallest number entered was: " + smallest);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值