mardi 16 février 2016

Trying to return a boolean value from a method to an if statement in main, but only true seems to be returned

Trying to return a boolean value from a method to an if statement in main, but only true seems to be returned. The method isAllEven should return a boolean whether each element in the array is even or not. However, the if statement "if(option == 1)" is only printing the output for even. I can't figure out why isAllEven won't return false.

import java.util.Scanner;
import java.util.Random;

public class Part1 {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String prompt = ("How many elements/list: ");
    int num = getInt(input, prompt);
    int[] list = initRand(num);

    System.out.println("The list is:");
    print(list);

    int option = menu();

   if(option == 1){
      boolean allEven = isAllEven(list);

      if(allEven = true)
        System.out.println("All values are even");
      else
        System.out.println("Some values/list are odd.");
    }



  }

  public static int[] initRand(int num){
    int[] list = new int[num];
    Random rand = new Random();
    for(int i=0; i<num; i++){
      list[i] = rand.nextInt(100-1)+1;
    }
    return list;
  }

  public static void print(int[] list){
    for(int i=0; i<list.length; i++){
      System.out.printf("%-5s", list[i]); 
    }
  }

  public static int menu(){
    System.out.println("\n\nYour options are:\n-----------------");
    System.out.println("1) All even values?");
    System.out.println("2) All unique values?");
    System.out.println("3) Print min gap between values");
    System.out.println("4) Statistics");
    System.out.println("5) Print 80% percentile ");
    System.out.println("0) EXIT");

    String prompt = "Please enter your option:";

    Scanner input = new Scanner(System.in);
    int option = getInt(input, prompt);

    if(option < 0 || option > 5)
      menu();
    else if(option == 0){
      System.out.print("Testing completed.");
      System.exit(0);
    }

    return option;
  }

  public static boolean isAllEven(int[] list){

    boolean allEven = true;

    for(int i=0; i<list.length; i++){
      if(list[i] % 2 != 0){
        allEven = false;
        break;
      }
    }
    return allEven;
  }

      public static int getInt(Scanner input, String prompt){
        System.out.print(prompt);
        while(!input.hasNextInt()){
        input.next(); 
        System.out.print("Not an integer! Try again! ");
        System.out.print(prompt);
       }
        return input.nextInt();
       }
    }

Aucun commentaire:

Enregistrer un commentaire