有 Java 编程相关的问题?

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

java无法将字符串更改为整数,因为负号跟在数字后面

我正在使用Java读取CSV文件,并对给定的项目进行一些数据分析。我读入的几个数据点是一组不同的数字,范围从-999到999。我想将这些数字相互比较,所以我首先将字符串转换为整数。 我遇到的问题是,CSV文件保存负数,负号紧跟在数字(1-)之后。这会引发NullFormatException。我觉得有一个简单的方法来解决这个问题,我忽略了。任何帮助都会很好

假设随机数据是{1,19,20,7,8},我需要{1,-19,-20,7,8}

int[] nnaOH = new int[x];
int[] nwOH = new int[x];
int[] nuaOH = new int[x];
for (int z = 1; z < x; z++){
    nnaOH[z] = Integer.parseInt(naOH[z]);
    nwOH[z] = Integer.parseInt(wOH[z]);
    nuaOH[z] = Integer.parseInt(uaOH[z]);
    }

共 (2) 个答案

  1. # 1 楼答案

    试试这样。它将检测结尾处的连字符,并在解析数字之前将其删除,将其设置为负值

    private int parseInt(String str) {
    
        if (str.endsWith("-")) {
            str = str.substring(0, str.length() - 1);
            return -Integer.parseInt(str);
        } else {
            return Integer.parseInt(str);
        }
    }
    
  2. # 2 楼答案

    可以使用DecimalFormat以自定义格式解析整数:

    import java.text.DecimalFormat;
    import java.text.ParseException;
    
    public class DecimalFormatTest {
    
        public static void main(String[] args) throws ParseException {
            DecimalFormat decimalFormat = new DecimalFormat("#;#-");
            System.out.println(decimalFormat.parse("123-").intValue());
            System.out.println(decimalFormat.parse("321").intValue());
        }
    }
    

    输出:

    -123
    321