[英]How do I check if the input is an integer? I have issue with the output when the user enter 7 the program end
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package validatinginput;
import java.util.Scanner;
/**
*
* @author abdal
*/
public class ValidatingInput {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Declare variables
int number = 0;
int lowerbound = 5;
int upperbound =10;
//Prompt the user to enter an interger between 5 and 10
System.out.println("Please enter a interger int between 5 and 10");
while (!s.hasNextInt()) {
System.out.println("Not an int");
s.next();
}
number = s.nextInt();
if (number<= lowerbound || number >= upperbound){
System.out.println("out bound");
number++;
}else{
System.out.println("you entered");
s.next();
}number = s.nextInt();
}
}
我认为这里有两个问题:
number = s.nextInt()
(等待更多输入)然后停止(从main
返回)。 您需要另一个循环,直到用户输入有效的 integer。number = s.nextInt()
从扫描仪中读取。 如果 integer 在您调用s.next()
和number =
s.nextInt() *again*. Both calls look suspicious/wrong: you already have the integer to be read in variable
*again*. Both calls look suspicious/wrong: you already have the integer to be read in variable
number . There is no need to read any more information from the scanner. In fact, the calls to
. There is no need to read any more information from the scanner. In fact, the calls to
. There is no need to read any more information from the scanner. In fact, the calls to
s.next() and
s.nextInt()` 的调用将阻塞,直到您输入更多数据。 在第一个number = s.nextInt()
行之后,您不应再调用s.nextXXX()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.