0

Here is my solution to Goldbach`s Conjecture problem for the numbers in the [m,n] interval. The code works but there is a problem with reading the values of a and m. Nothing happens if I do not introduce more than 2 input values ( like 4 or more). If I do so, the first value is assigned to m and the last one to n. Why is this happening? How can I correct it?

public class GoldbachConjecture {

    public static void Goldbach(int x) {
        int ok=0;
        for (int i = 3; i < x / 2 && ok==0; i++) {
            if (isPrime(i) && isPrime(x - i)) {
                System.out.println("The number is " + x + " Prime Numbers are " + i + " " + (x - i));
                ok=1;
            }
        }
    }

    public static boolean isPrime(int x) {
        for (int i = 2; i < x / 2; i++) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }


    public static void main(String[] args) {


        System.out.print("Give the interval" );

        Scanner in1= new Scanner(System.in);
        int m = in1.nextInt();

        Scanner in2=new Scanner(System.in);
        int n=in2.nextInt();

        for(int nr = m; nr <= n; nr++)
        {
         if(nr>2 && nr%2==0) 
              Goldbach(nr);
          } 
}
}
K Scandrett
  • 15,287
  • 4
  • 33
  • 59
Ana-Maria
  • 63
  • 1
  • 8
  • You don't need more than 2 numbers as input. You just can't enter them into the same line, due to your bad choice of using two independent `Scanner` instances. – Tom Oct 23 '16 at 06:06

1 Answers1

0

Firs of all, you should use only one Scanner. I think the problem lies in the fact that Scanner.nextInt() doesn't "consume" the new line character of your input (the one that you type when you hit enter in the terminal).

One workaround is calling Scanner.nextLine() after Scanner.nextInt().

Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
sc.nextLine(); // consuming last new line.

UPDATE: You can try this workaround too (as seen in https://stackoverflow.com/a/13102066/4208583):

Scanner sc = new Scanner(System.in);
int m;
try {
    m = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
Community
  • 1
  • 1
Grender
  • 1,478
  • 1
  • 14
  • 39
  • You can keep the first sentence, but the other stuff isn't correct here. There is no need to consume remaining line endings in OPs code. – Tom Oct 23 '16 at 06:05