import java.util.*;
public class MainClass {
public static void main(String[] args) {
System.out.println("Enter the Number you want the Maximum times the Pattern to Print while Increasing 1 each Time :");
boolean isInteger = true;
do {
Scanner Obj = new Scanner(System.in);
int a = Obj.nextInt();
if (a.hasNextInt()) { // Line 10 : THE Condition i want is to check if INPUT 'a' has a integer Value and execute rest of the code on the condition.
int i;
for (i=1;i<=a;i++){
int j;
for (j=1;j<=i;j++) {
System.out.println("a");
}
System.out.println();
}
}
else {
System.out.println("Please Enter a Integer Value : ");
isInteger = false;
}
} while (isInteger == false);
}
}
/*in the Above Code while i was Trying to Print
*
**
***
****
*/
模式类型多次,然后我想通过获取用户输入来执行此操作,并且我想检查用户输入是否是整数,然后仅执行其余代码,否则它应该返回“请输入整数值:”并将用户发送回输入另一个输入 - 我是 Java 新手。
如何检查输入的值是否为整数? 10号线。
使用 next() 而不是 nextInt() 并检查该值是字符串还是数字以避免默认错误。 尝试这样
System.out.println("Enter the Number you want the Maximum times the Pattern to Print while Increasing 1 each Time :\n");
boolean isInteger = true;
do {
Scanner Obj = new Scanner(System.in);
String userInput = Obj.next();
int number = 0;
try {
number = Integer.parseInt(userInput);
isInteger = true;
} catch(Exception e) {
isInteger = false;
}
if(isInteger) {
int i, j;
for (i = 1; i <= number; i++) {
for (j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
} else {
System.out.println("Please Enter a Integer Value - " + userInput);
}
} while (isInteger == false);