mercredi 9 décembre 2020

I have a problem with splitting up my Java program into separate methods within the same class, could I have some advice on how to go about it?

I was given the task of splitting my program which which allows the user to enter an array of numbers and after an odd number between 1 and 10 to check whether the odd number is a factor of each of the 5 numbers in the array. I keep on trying out different ways but none seem to work. Could someone help me out or send a sample of how I should sort it? This is the program:

import java.util.Scanner;
public class CheckboxExample{  
    public static void main(String args[])  {  
        CheckBox c = new CheckBox();
        new CheckboxExample();  // links to checkbox class
        Scanner s = new Scanner(System.in);
        int array[] = new int[10]; 
        System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
        int num; // declares variable num
        try{
            for (int i = 0; i < 10; i++) {
                array[i] = s.nextInt(); // array declaration
            }
        }catch (Exception e){
            System.out.println ("You have an error");
        }

        System.out.println ("Please enter an odd number between 1 and 10");

        try{
            num = s.nextInt ();
            if (num % 2 == 0){
                do{
                    System.out.println ("\nYour number is even, enter an odd one");
                    num = s.nextInt ();
                }while (num % 2 == 0);
            } 

            if (num < 0 | num > 10){
                do{  
                    System.out.println ("Your number is outside of the range, try again");
                    num = s.nextInt ();  
                }while (num < 0 | num > 10);
            } 

            for (int i = 0; i < 5 ; i++){
                if (array[i] % num  == 0) {
                    System.out.println("Your number is a factor of " + array[i] );
                } 
            }
        }catch (Exception e){
            System.out.println ("error");
        }
    }  
}  



Aucun commentaire:

Enregistrer un commentaire