简体   繁体   English

如何使用parseInt将字符串转换为整数?

[英]How to convert string to integer with parseInt?

I have this code: 我有以下代码:

public static void main(String[] args) {
        List<Valtozas> lista = new ArrayList<Valtozas>();

        try {
            File fajl = new File("c://data//uzemanyag.txt");
            Scanner szkenner = new Scanner(fajl, "UTF8");

            while (szkenner.hasNext()) {
                String sor = szkenner.nextLine();
                String [] darabok = sor.split(";");
                String szoveg = darabok[0];
                Valtozas valtozas = new Valtozas(Integer.valueOf(darabok[0]), Integer.valueOf(darabok[1]), Integer.valueOf(darabok[2]));
                lista.add(valtozas);
            }
        }
        catch (Exception e) {

        }


        //3.FELADAT
        System.out.println("3.Feladat: Változások száma: "+lista.size());
    }

}

Here I want to convert the String to int, but I cant. 在这里,我想将String转换为int,但是我不能。 I tried the Integer.Valueof(darabok[0]), but its not working. 我尝试了Integer.Valueof(darabok [0]),但是它不起作用。 And nothing is happening, so the code is build, but quit from the while. 而且什么也没有发生,因此代码得以构建,但从此退出。

Based on the source code you have shown us, the problem is that there is a format mismatch between the input file and the program you are trying to read. 根据您显示给我们的源代码,问题在于输入文件和您尝试读取的程序之间存在格式不匹配。

The program reads the file a line at a time, and splits it into fields using a single semicolon (with no whitespace!) as the file separator. 该程序一次读取一行文件,然后使用单个分号(无空格!)作为文件分隔符将其拆分为多个字段。 Then it tries to parse the first three fields of each split line as integers. 然后,它尝试将每个分割线的前三个字段解析为整数。

For this to work the following must be true: 为此,必须满足以下条件:

  • Every line must have at least three fields. 每行必须至少包含三个字段。 (Otherwise you will get a ArrayIndexOutOfBound exception.) (否则,您将获得ArrayIndexOutOfBound异常。)
  • The three fields must match the following regex: -?[0-9]+ ie an optional minus signed followed by one or more decimal digits. 这三个字段必须与以下正则表达式匹配: -?[0-9]+ ,即可选的负号,后跟一个或多个十进制数字。
  • The resulting number must be between Integer.MIN_VALUE and Integer.MAX_VALUE . 结果数字必须在Integer.MIN_VALUEInteger.MAX_VALUE之间。

Elaborating on the above: 详细说明:

  • Leading and trailing whitespace characters are not allowed. 不允许使用前导和尾随空格字符。
  • Embedded decimals markers and grouping characters are not allowed. 不允许嵌入小数点标记和分组字符。
  • Scientific notation is not allowed. 不允许使用科学计数法。
  • Numbers that are too large or too small are not allowed. 不允许数字太大或太小。

Note that if any of the above constraints is not met, then the runtime system will throw an exception. 请注意,如果不满足上述任何约束,则运行时系统将引发异常。 Unfortunately, you surround your code with this: 不幸的是,您用以下代码包围了代码:

    try {
        ...
    }
    catch (Exception e) {

    }

That basically ignores all exceptions by catching them and doing nothing in the handler block. 通过捕获异常并在处理程序块中不执行任何操作,基本上可以忽略所有异常。 You are saying to Java "if anything goes wrong, don't tell me about it!". 您是在对Java说“如果有任何问题,请不要告诉我!”。 So, naturally, Java doesn't tell you what is going wrong. 因此,自然,Java不会告诉您出了什么问题。

DON'T EVER DO THIS . 永远不要这样 This is called exception squashing, and it is a really bad idea 1 . 这被称为异常压缩,这是一个非常糟糕的主意1

There are two ways to address this: 有两种解决方法:

  1. Print or log the stacktrace; 打印或记录堆栈跟踪; eg 例如

      catch (Exception e) { e.printStackTrace(); } 
  2. Remove the try / catch, and add throws IOException to the signature of your main method. 删除try / catch,然后向main方法的签名中添加throws IOException

(You can't just remove the try / catch because new Scanner(fajl, "UTF8") throws IOException . That's a checked exception so must be handled or declared in the method signature.) (您不能删除try / catch,因为new Scanner(fajl, "UTF8")抛出IOException 。这是一个已检查的异常,因此必须在方法签名中进行处理或声明。)

Once you have dealt with the exception properly you will get an exception message and stacktrace that tells you what is actually going wrong. 正确处理了异常后,您将获得一条异常消息和stacktrace,告诉您实际出了什么问题。 Read it, understand it, and fix your program. 阅读,理解并修复程序。


1 - It is like taping over the "annoying" red light that indicates that your car's oil level is low! 1-就像点击“烦人”的红灯一样,表示您的汽车油位低!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用 Integer.parseInt() 的情况下将字符串值转换为整数? - how to convert a string value to integer without using Integer.parseInt()? 将长字符串转换为整数而不使用parseLong或parseInt - Convert long string to integer without parseLong or parseInt Integer.parseInt无法将输入字符串“ 1”转换为整数 - Integer.parseInt couldn't convert to integer for input string “1” 不可能使用 Integer.parseInt() 将字符串数组转换为整数数组 - Convert string array to integer array using Integer.parseInt() not possible 尝试使用 Integer.parseInt() 将字符串转换为 integer 时出错 - Error when trying to convert string to integer using Integer.parseInt() Integer.parseInt 是在 Java 中将 String 转换为 Int 的最佳方式吗? - Integer.parseInt is best way to convert String to Int in Java? 即使在Java中使用parseInt,也无法将二进制字符串转换为整数 - Unable to convert binary string to integer despite using parseInt in java 使用Integer.parseInt将String转换为Int不起作用 - Convert String to Int with Integer.parseInt don't works 是否可以使用Integer.parseInt(String)将通过获取字符串额外获得的意图获取的String值转换为整数 - Is it possible to convert the String value we are getting by intent via get string extra into integer with Integer.parseInt(String) 使用parseint将String转换为int - convert String to int with with parseint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM