Search code examples
javastringintegernumberformatexception

How to counter a java.lang.NumberFormatException in the following code?


I'm trying to find maximum XOR value. I'm converting the Strings p and q into the Integers n and m so I can check the exclusivity but I'm encountering a java.lang.NumberFormatException. How do I deal with that?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int maxXor(int l, int r) {
        String p = " ";
        String q = " ";
        String s = " ";
        int sum = 0;
        do {
            p = (l % 2) + p;
            q = (r % 2) + q;
            l = l / 2;
            r = r / 2;
        } while ((l > 0) && (r > 0));
        int n = Integer.valueOf(p);
        int m = Integer.valueOf(q);
        while ((n != 0) && (m != 0)) {
            if ((n % 10) == (m % 10)) {
                s = s + "0";
            } else {
                s = s + "1";
            }
        }
        System.out.println(s);
        int len = s.length();
        int x = Integer.parseInt(s);
        for (int i = 1; i <= len; i++) {
            int d = x % 10;
            sum = (sum * 10) + d;
            x = x / 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;
        int _l;
        _l = Integer.parseInt(in.nextLine());
        int _r;
        _r = Integer.parseInt(in.nextLine());
        res = maxXor(_l, _r);
        System.out.println(res);
    }
}

Solution

  • int n = Integer.valueOf(p.trim());
    int m = Integer.valueOf(q.trim());
    

    This should do the trick.