简体   繁体   中英

A different approach to comparing integers with strings in java?

I have a program that goes through each string in a text file. I want to compare these strings to an "ID" number that i have. In this case im using Integer.parseInt() which throws a NumberFormatException when the string im comparing has characters in it. Is there another way I can compare an integer with strings without running into this error?

            int num;
            int ID = 354;
            Scanner sc2 = null;

            try {
                sc2 = new Scanner(new File("Database.txt"));
            } 
            catch (FileNotFoundException e) 
            {
                e.printStackTrace();  
            }
            while (sc2.hasNextLine()) 
            {
                Scanner s2 = new Scanner(sc2.nextLine());
                while (s2.hasNext()) 
                {
                    String s = s2.next();
                    System.out.println(s);
                    num = Integer.parseInt(s);
                    if(num == ID)
                    {
                        System.out.println("Success.");
                    }
                }
            }

您可以将ID转换为字符串并使用equals() (效率低下,但代码更少),或者可以捕获NumberFormatException并continue while循环(忽略无法解析为整数的行)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM