3 回答
TA贡献1836条经验 获得超3个赞
我稍微更改了您的代码并将其作为一个整体发布,以避免混淆:
public static void main(String[] args) {
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do {
int integer = Integer.MAX_VALUE;
while (integer == Integer.MAX_VALUE) {
// Get input from the user
System.out.print("Enter an integer: ");
String input = sc.nextLine();
try {
integer = Integer.parseInt(input);
}
catch (NumberFormatException e) {
System.out.println("Error! Invalid integer. Try again.");
}
}
if(integer<0){
System.out.println("Error! Number must be greater than 0");
System.out.print("Enter an integer: ");
integer = sc.nextInt();
}
if(integer>100){
System.out.println("Error! Number must be less than or equal to 100");
System.out.print("Enter an integer: ");
integer = sc.nextInt();
}
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
} while (!choice.equalsIgnoreCase("n"));
}
这个想法是while在你的循环中创建另一个并运行它直到用户传递一个整数。
TA贡献1804条经验 获得超7个赞
Integer.parseInt方法是将 the 转换String为 int 并NumberFormatException在字符串无法转换为int类型时抛出 a 。
应该是这样的:
System.out.print("Enter an integer: ");
Scanner sc =new Scanner(System.in);
try {
int integer = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error! Invalid integer. Try again.");
}
TA贡献1876条经验 获得超5个赞
您可以使用此方法来测试输入的值是否为有效整数。以此结果为基础,您可以从其他验证开始
public boolean isInt(string input) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
添加回答
举报