找出用户是否输入了字符串,整数或双精度值

时间:2016-08-02 07:04:56

标签: java java.util.scanner

Scanner sc = new Scanner(System.in);
System.out.println("Enter whatever you want");
String st = sc.nextLine();
try {
    String d = String.valueOf(st);
    if (d == (String) d) {
        System.out.println((String) d);
    } else {
        System.out.println(d);
    }
} catch(Exception e) {
    System.out.println("integer");
}

当我尝试执行此操作时,它会继续打印“if”部分,即使是整数和双精度。

4 个答案:

答案 0 :(得分:1)

为了使用您的代码: 尝试先解析为整数。如果这是成功的,则意味着你有一个int。如果这不起作用,请尝试解析为double,如果这有效,则意味着你有一个double,否则你有一个字符串。

使用<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"> Post: </string> Integer.valueOf

Double.valueOf

但我不会这样建造它。更好的选择是使用 System.out.println("Enter whatever you want"); String st = sc.nextLine(); try { Integer d = Integer.valueOf(st); System.out.println("Integer: " + d); } catch (NumberFormatException e) { try { Double d = Double.valueOf(st); System.out.println("Double: " + d); }catch (NumberFormatException nf) { System.out.println("String: " + st); } } sc.hasNextInt

答案 1 :(得分:1)

任何输入都可以作为字符串进行评估,即使它是&#34; 2.9&#34;。相反,您可以使用Scanner<?php $errors = []; if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_POST['grade1'] < 0) { $errors['grade1'] = 'Too low'; } ... if (!$errors) { // validation successful, do something } } ?> <form method="post"> <input name="grade1" value="<?= htmlspecialchars($_POST['grade1'] ?? null); ?>"> <?php if (isset($errors['grade1'])) : ?> <span class="error"><?= $errors['grade1']; ?></span> <?php endif; ?> ... </form> 方法:

hasXYZ

答案 2 :(得分:0)

您可以使用此程序输出类型:

import java.util.Scanner;

public class MyTest {
public static void main(String args[]) throws Exception {
    Scanner sc = new Scanner(System.in);

    System.out.println("Enter whatever you want");

    String st = sc.nextLine();
    try {
        Integer.parseInt(st);
        System.out.println("Integer");
    } catch (NumberFormatException nfe) {

        try {
            Double.parseDouble(st);
            System.out.println("Double");
        } catch (NumberFormatException nfe2) {
            System.out.println("String");
        }

    }
    sc.close();
}
}

答案 3 :(得分:-1)

试试这个:

String d= String.valueOf(st);
try{
 //If double or integer comes here
  double val = Double.parseDouble(d);
}catch(Exception e){
  //If String comes here
}