【问题标题】:Error While converting a String to an Int Java将字符串转换为 Int Java 时出错
【发布时间】:2020-08-02 22:17:39
【问题描述】:

所以我收到一个 IP/PortNumber:WaitTime 形式的字符串作为字符串。我在“:”上将这两个分开,所以我收到两部分,IP/Potnumber 作为一个,WaitTime 作为另一个字符串。我试图将此字符串转换为 int,但我不断收到字符串无效的错误。

错误:

][3]

public static int GetJob (String recieved) {
    String[] arrOfJob = recieved.split(":");
    int accjob =0;
    try {
        accjob = Integer.parseInt(arrOfJob[1]);
    } catch(NumberFormatException ex){
        System.out.println(ex);
    }
    return accjob;
}


public static int GetJob (String recieved) {
    String[] arrOfJob = recieved.split(":");
    int accjob =0;
    System.out.print("/"+arrOfJob[1]+"/");
    try {
        accjob = Integer.parseInt(arrOfJob[1]);
    } catch(NumberFormatException ex){
        System.out.println(ex);
    }
    return accjob;
}

【问题讨论】:

  • 发布错误。
  • 错误发布为图片
  • 您的代码在我身边工作,用于输入:192.168.229.1/3900:1000。你能检查一下你是否正在使用任何空间或使用trim()
  • 为什么会出现这个错误?
  • 输入"192.168.229.1/3900:1000"的代码没有问题

标签: java string parsing integer


【解决方案1】:

试试java中的instanceof,看看你解析的是string还是double或者其他数据类型。

例子:

Integer i = 0;
if(i instanceof Integer) {
    System.out.println("true");
}

输出:

true

确保变量应该是对象(Integer,Double,..) 而不是原始类型(int,double,..)。

NumberFormatException 将发生在不可解析值的原因。

【讨论】:

    【解决方案2】:

    试试这个:

        public static int getJob(String input) {
            String[] split = input.split(":");
            try {
                return Integer.parseInt(split[1].trim());
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
            }
            return -1;
        }
    

    【讨论】:

    • 这行得通!非常感谢。我哪里做错了?
    • 我认为,您的输入中有空格。导致问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2013-11-03
    • 1970-01-01
    • 2011-09-15
    • 2013-05-17
    • 2016-07-07
    • 2021-08-01
    相关资源
    最近更新 更多