我希望用户仅输入整数,如果他输入其他任何内容,都应该得到我的错误,并应要求再次输入。但是此代码无法正常运行,因为我希望我的程序能够运行。请为此提供帮助,也欢迎其他建议。
//this is a separate main file
import java.util.*;
public class SolMul {
public static void main(String[] args) {
int g = 1;
Scanner input = new Scanner(System.in);
do{
try{
System.out.println("Please enter the number you want the table for: \n");
int z = input.nextInt();
System.out.println("Upto what number you want the table:\n");
int y = input.nextInt();
Solve multiplyObj = new Solve();
multiplyObj.multiply(z, y);
g = 2;
}catch(InputMismatchException e){
System.out.println("Error");
}
}
while(g==1);
input.close();
}
}
//this is a separate class file in a new window
public class Solve {
public void multiply(int number,int upto){
for (int x = 1; x <= upto; x ++){
System.out.printf("%d X %d = %d \n",number,x,number*x );
}
}
}
第一的,
input.nextInt()
不捕获换行符。因此,您需要将其替换为input.nextLine()
。
int z = Integer.parseInt(input.nextLine());
int y = Integer.parseInt(input.nextLine());
您可以添加一个Exception catch块来处理任何解析错误。对您的代码进行更改。
public static void main(String[] args) {
int g = 1;
Scanner input = new Scanner(System.in);
do {
try {
System.out.println("Please enter the number you want the table for: \n");
int z = Integer.parseInt(input.nextLine());
System.out.println("Upto what number you want the table:\n");
int y = Integer.parseInt(input.nextLine());
Solve multiplyObj = new Solve();
multiplyObj.multiply(z, y);
g = 2;
} catch (InputMismatchException e) {
System.out.println("Error -- input again");
}catch (Exception e) {
System.out.println("Error -- input again");
}
}while (g == 1);
input.close();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加