0
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);    
     }

}   

使用此代码,我只能生成一个整数。如果我想生成一个带小数的双精度,我该怎么做?

4

3 回答 3

1

您可以尝试使用Integer.parseIntDouble.parseDouble解析整数或双精度值。

于 2013-09-23T01:01:06.690 回答
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
于 2013-09-23T01:05:52.850 回答
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 的答案!)。

于 2013-09-23T01:03:39.020 回答