有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中解析字符串中的int、double和String

我必须在Java类中使用Scanner方法进行赋值,以输入整数(项目数)、字符串(项目名称)和双精度(项目成本)。我们必须使用Scanner.nextLine(),然后从那里解析

例如:

System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();         

用户将输入如下内容:3 Captain Crunch 3.5

输出将是:Captain Crunch #3 for $10.5

我遇到的问题是解析字符串中的int和double,但同时保留字符串值


共 (3) 个答案

  1. # 1 楼答案

        Scanner sc = new Scanner(System.in);
        String message = sc.nextLine();//take the message from the command line
        String temp [] = message.split(" ");// assign to a temp array value
        int number = Integer.parseInt(temp[0]);// take the first value from the message
        String name = temp[1]; // second one is name.
        Double price = Double.parseDouble(temp[2]); // third one is price
        System.out.println(name +  " #" + number + " for $ "  + number*price ) ;
    
  2. # 2 楼答案

    如果我理解你的问题,你可以用^{}^{}之类的词

    String input = "3 Captain Crunch 3.5";
    int fi = input.indexOf(' ');
    int li = input.lastIndexOf(' ');
    int itemNumber = Integer.parseInt(input.substring(0, fi));
    double price = Double.parseDouble(input.substring(li + 1));
    System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
                itemNumber, itemNumber * price);
    

    输出是

    Captain Crunch #3 for $10.50
    
  3. # 3 楼答案

    1. 首先,拆分字符串并获得一个数组
    2. 在阵列中循环
    3. 然后,您可以尝试将数组中的这些字符串解析为各自的类型

    例如: 在每次迭代中,查看它是否为整数。下面的示例检查第一个元素是否为整数

    string[0].matches("\\d+")
    

    或者你可以使用try catch如下(但不推荐)

    try{
       int anInteger = Integer.parseInt(string[0]);
       }catch(NumberFormatException e){
    
       }