int s;
number2=input.next();
for (int i=0;i<number2.length();i++){
s=(int)(number2.charAt(i));
while ((s<48)||(s>57)){
System.out.println("Enter the amount");
number2=input.next();
s=number2.charAt(i);
}
}
使用此代码我只能生成一个整数。如果我想生成带小数的double,我该怎么做?
答案 0 :(得分:1)
您可以尝试使用Integer.parseInt
或Double.parseDouble
来解析整数字符串或双精度值。
答案 1 :(得分:1)
你可以作弊......
String text = "123";
boolean isDouble = false;
boolean isInt = false;
try {
Double.parseDouble(text);
try {
Integer.parseInt(text);
isInt = true;
} catch (NumberFormatException exp) {
isDouble = true;
}
System.out.println("isInt = " + isInt);
System.out.println("isDouble = " + isDouble);
} catch (NumberFormatException exp) {
System.out.println(text + " is not a valid number");
}
A123
输出A123 is not a valid number
...
123
输出......
isInt = true
isDouble = false
123.321
输出......
isInt = false
isDouble = true
答案 2 :(得分:0)
假设您正在阅读用户的输入,您可以使用nextInt()
:
Scanner scan = new Scanner(System.in);
int n = 0;
try{
n = scan.nextInt();
}
catch(NumberFormatException e){
//do here what you want to do in case it's not an int
}
如果输入不是int,请不要忘记使用try / catch(同样适用于Juned的答案!)。