Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Exam_Problem3_Biggest3PrimeNumbers {
public static void main(String[] args) {
List<String> inputNums= new ArrayList<>();
List<Integer> intList=new ArrayList<>();
List<Integer> primeNums=new ArrayList<>();
//input
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
//numbers from input as str
Pattern nums = Pattern
.compile("[0-9]+");
Matcher matcher = nums.matcher(input);
while (matcher.find()) {
inputNums.add(matcher.group());
}
//str to int intList contains all nums
for(String inputNum : inputNums) intList.add(Integer.valueOf(inputNum));
for (int temp = intList.size(),i=0; i < temp; i++) {
int n=intList.get(i);
//check for prime numbers
if(n>=2){
boolean isPrime=true;
for (int ii = 2; ii < n; ii++) {
if (n % ii == 0) {
isPrime = false;
}}
if ((isPrime)||(n==2)){
primeNums.add(n);
}
}
}
for (int temp = primeNums.size(), i = 0; i < temp; i++) {
int inputNum = primeNums.get(i);
}
//primeHash - no duplicates
Set<Integer> primeHash = new HashSet<Integer>(primeNums);
//primeHash>=3 means more or equal to 3 prime numbers
if(primeHash.size()>=3){
int lenHash=primeHash.size();
Object[] primeObject=primeHash.toArray();
int lenObj=primeObject.length;
int arr[]=new int[lenHash];
for (int i = 0; i < lenObj; i++) {
arr[i]=(int) primeObject[i];
}
Arrays.sort(arr);
int num1=arr[lenObj-1];
int num2=arr[lenObj-2];
int num3=arr[lenObj-3];
int sum=num1+num2+num3;
System.out.println(sum);
}else{
System.out.println("No");
}
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment