以下是我在c / c ++中使用的一段相当简单的代码:
while ((scanf_s("%d", &num) == 1)&&num>0)
以下是通常用于读取输入的java代码:
try(Scanner n1 = new Scanner(System.in))
{
System.out.println("Enter the number of days");
while(n1.hasNextInt())
{
days = n1.nextInt();
//some stmts
n1.nextLine();
}
}
如何在阅读输入的同时使用它来比较单个“中的值”,就像我在c和c ++中可以做的那样;
答案 0 :(得分:1)
你可以这样:
int num;
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt() && (num = scanner.nextInt()) > 0) {
// do something with num
}
答案 1 :(得分:0)
或者,您可以这样做:
int input;
final Scanner scanner = new Scanner(System.in);
System.out.print("Type anything: ");
try
{
input = scanner.nextInt();
System.out.println("You typed: " + input);
}
catch (InputMismatchException e)
{
System.out.println("You typed a non-numeric value or the value entered is out of range.");
}
如果输入不是数字或超出范围,您可以处理异常。