输入验证和错误输出

时间:2017-03-18 23:34:45

标签: java

现在正在阅读包含

的文件
3
6
8 9 11
-123
7
12,

输出

3 - prime, palindrome, emirp
6 - even, palindrome,
8 - even, palindrome,
-123 - invalid input
7 - invalid input

但是,7不应该是无效输入,并且会完全跳过12,,这应该显示为无效输入。我不知道如何编写用于将12,12.12-视为无效的代码,但没有让我的程序将我文件中的每个最后一个数字视为无效输入。

感谢您的帮助!

以下是我正在使用的代码的一部分

if (inputFile.exists()) {
    Scanner read = new Scanner(inputFile);

    while (read.hasNextInt()) {
        int number = read.nextInt();
        if (number <=0 || !read.hasNextInt()) {
            System.out.println(number + " - invalid input");
        } else {
            System.out.print(number + " - ");
            if(isEven(number))
                System.out.print("even, ");
            if(isPrime(number))
                System.out.print("prime, ");
            if(isPalin(number))
                System.out.print("palindrome, ");
            if(isEmirp(number))
                System.out.print("emirp");
            System.out.println();
            read.nextLine();
        }
    }
    read.close();
}

编辑代码:

while (read.hasNext()) { // continue while there are tokens left
if (read.hasNextInt()) { // check if next token is int
int number = read.nextInt(); // get next int token
if (number <= 0) {System.out.println(number + " - invalid input");}
else{
System.out.print(number + " " + "- ");
if(isEven(number)){
System.out.print("even"+","+ " ");}
if(isPrime(number)){
System.out.print("prime"+ "," +" ");}
if(isPalin(number)){
System.out.print("palindrome"+"," + " ");}
if(isEmirp(number)){
System.out.print("emirp");}

else { 
String s = read.next(); 
System.out.print(s + " - invalid input");
System.out.println("");
read.nextLine();

1 个答案:

答案 0 :(得分:0)

您可以在此行中找到7被标记为无效的原因:

if (number <= 0 || !read.hasNextInt()) {

下一个标记是12,,它不是有效的int。这就是为什么这个表达式导致true以及为什么7被标记为无效的原因。要更正此问题,请使用以下行替换上述行:

if (number <= 0) {

修改

主while循环仅在下一个标记为int时才会继续。但是对于12,,情况并非如此。你必须做一些改动才能按照你想要的方式工作:

while (read.hasNext()) { // continue while there are tokens left
    if (read.hasNextInt()) { // check if next token is int
        int number = read.nextInt(); // get next int token
        if (number <= 0) {
            System.out.println(number + " - invalid input");
        } else {
            // etc...
        }
    } else { // next token is not int
        String s = read.next(); // get next non-int token
        System.out.println(s + " - invalid input"); // print invalid input
    }
}