我试图问用户两个两位数字,然后对两个数字进行长度检查和类型检查,然后我想输出数字的总和。这是我到目前为止的内容:
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);
}
}
目前,我的程序甚至都不会要求我进行第二次输入。不知道该怎么办:/
答案 0 :(得分:1)
几件事:
-不要构造多个Scanner
对象以从System.in
中读取。只会造成问题。
-您正在使用String.valueOf()
将int转换为String
。最好只检查一下以确保它在10到99之间。
-您检查以确保Scanner
在调用nextInt
后没有下一个int ,这对您没有帮助。您需要确保存在下一个整数。
-您的许多if
语句都有一个空的if
块,然后您在其他语句中进行操作。您可以在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);