我试图问用户两个两位数的数字,然后对两个数字都进行长度检查和类型检查,然后我想输出数字的总和。这是我到目前为止的内容:

package codething;

import java.util.Scanner;
public class Practice {

    public static void main(String[] args) {
        Scanner number = new Scanner(System.in);  // Reading from System.in
        System.out.println("Enter a two digit number (10-99) ");
        int n = number.nextInt();

                if(number.hasNextInt()) {
                } else {
                System.out.println("Error");
                }

        int m;



        int length = String.valueOf(number).length();
        if (length == 2) {
        } else {
           System.out.println("this isnt a valid input and you have killed my program ;(");
        }

        Scanner number1 = new Scanner(System.in);
        System.out.println("Enter another two digit number (10-99) ");
                        m = number.nextInt();

                    if(number1.hasNextInt()) {
                        m = number1.nextInt();
                    } else {
                        System.out.println("Error");
                    }

        int sum = n + m;
        System.out.println(sum);
    }
}


目前,我的程序甚至都不会要求我进行第二次输入。不知道该怎么办 :/

最佳答案

有几件事:

-不要构造多个从Scanner读取的System.in对象。它只会引起问题。

-您正在使用String.valueOf()将int转换为String。最好只检查一下以确保它在10到99之间。

-在调用Scanner后,请检查以确保nextInt具有下一个int,这将无济于事。您需要确保存在下一个int。

-很多if语句都有一个空的if块,然后在else中执行某些操作。您可以在if中执行相反的操作并省略else(可以代替if(length ==2) {}来执行if(length != 2) {//code}

Scanner number = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
 if(number.hasNextInt()) {
     n = number.nextInt();
 } else {
    number.next();  //Clear bad input
    System.out.println("Invalid");
}

int m = 0;


if ( n< 10 || n > 99) {
   System.out.println("this isnt a valid input and you have killed my program ;(");
}


System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
     m = number.nextInt();
} else {
    number.next();
    System.out.println("Invalid");
}

if (n< 10 || n > 99) {
    System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);

关于java - 试图学习如何对我的代码进行错误检查,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52524018/

10-12 00:13
查看更多