I am not sure what's wrong. The requirements did not state that a method must be created so I opted to for the longer approach.
lines 39-47 Factorize each number A & B then added them to lists
lines 50-55 compares the two lists
line 58 - on
//GCD is the largest number in both lists
package com.codegym.task.task14.task1420;
/*
GCD
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public static void main(String[] args) throws Exception {
/*1. The program should read 2 lines from the keyboard.
2. If the entered lines can't be converted to positive integers, throw an exception.
3. The program should display data on the screen.
4. The program should display the greatest common divisor (GCD)
of the numbers read from the keyboard and then terminate successfully.
The GCD is largest number that divides both the dividend and divisor evenly
*/
/* for this problem I can use the Euclidian Algorithm
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> numList = new ArrayList<Integer>();
for (int i = 0; i < 2; i++){
int x = Integer.parseInt(reader.readLine());
if (x < 0)
throw new Exception();
else
numList.add(x);
}
ArrayList<Integer> factorList1 = new ArrayList<Integer>();
ArrayList<Integer> factorList2 = new ArrayList<Integer>();
Integer A = Collections.max(numList);
Integer B = Collections.min(numList);
for(int i = 1; i<A; i++){
if (A%i ==0)
factorList1.add(i);
}
//System.out.println(factorList1.toString());
for(int i = 1; i<B; i++){
if (B%i ==0)
factorList2.add(i);
}
//System.out.println(factorList2.toString());
ArrayList<Integer> factorList3 = new ArrayList<Integer>();
int gcd = 0;
for (Integer i : factorList1){
if(factorList2.contains(i))
factorList3.add(i);
}
//System.out.println(factorList3.toString());
for (int i = 0; i<factorList3.size(); i++){
gcd = factorList3.get(factorList3.size()-1);
}
System.out.println(gcd);
}
}