Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.0 kB
2
Indexable
Never
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    static boolean checkPrime(String s){
        int x=Integer.parseInt(s);
        boolean flag=true;
        for (int i=2; i<=x/2 ;i++){
            if(x%i==0){
                flag=false;
                break;
            }
        }
        if(x==1){
            flag=false;
        }
        return flag;
    }
    static boolean checkPattern(int kthIndex,int prev){
        return kthIndex == prev || kthIndex == (prev - 1) || kthIndex == (prev + 1);
    }
    public static void main(String[] args) {

        int sum = 0;
        int prevStep=0;
        int maxNumber;
        int indexOfMax=0;
        int i;
        try {
            FileWriter fw=new FileWriter("myFile.txt");
            fw.write("1\n" +
                    "8 4\n" +
                    "2 6 9\n" +
                    "8 5 9 3\n");
            fw.close();
            FileReader fr = new FileReader("myFile.txt");
            Scanner reader = new Scanner(fr);
            while (reader.hasNextLine()) {
                String input = reader.nextLine();
                String[] splittedInput = input.split(" ");
                maxNumber=0;
                for (i = 0; i < splittedInput.length; i++) {
                    if(Integer.parseInt(splittedInput[i])>maxNumber &&(!checkPrime(splittedInput[i]))&&checkPattern(i,prevStep)){
                    maxNumber=Integer.parseInt(splittedInput[i]);
                    indexOfMax= i;
                    }
                }
                prevStep=indexOfMax;
                sum+=maxNumber;
                System.out.println("The largest non-prime number of the row "+i +" is "+ maxNumber);

            }
        } catch (IOException e){
            e.printStackTrace();
        }
        System.out.println("The maximum sum is "+sum);
    }
}