jeudi 18 novembre 2021

Result when the sum value is '8' should be even, yet it says odd

I've been looking at the code that I've written for few hours. I tried looking at other people's solution, compare and applied to my code but still my code doesn't work as it supposed to. I tried checking on the indentation, changing the name2.equals() with name2.equalsIgnoreCase(), still my code doesn't work as I expect. Can you please have a look at my code?

import java.util.*;
import java.util.Scanner;

public class OddsAndEvens {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Let's play a game called \"Odds and Evens\"");
        System.out.println("What is your name? ");
        String name = input.next();
        System.out.println("Hi "+name+", which do you choose? (O)dds or (E)vens?");
        String name2 = input.next();

        if (name2.equals("O")) {
            System.out.println(name+" has picked "+name2+"! The computer will be evens.");
        } else if (name2.equals("E")) {
            System.out.println(name+" has picked "+name2+"! The computer will be odds.");
            }
        else {
            System.out.println("Please pick either odds or evens!");
        }
        
        System.out.println("-----------------------------------------------------------");
        System.out.println("How many \"fingers\" do you put out?");
        int userNumber = input.nextInt();

        Random rand = new Random();
        int computer = rand.nextInt(6);
        System.out.println("The computer plays number "+computer);
        System.out.println("-----------------------------------------------------------");
        int sum = computer + userNumber;
        System.out.println("The sum is "+ sum);

        boolean oddOrEven = sum % 2 == 0;

        if (oddOrEven) {
            if (name2.equals("E")) {
                System.out.println(sum+" is even..!");
                System.out.println(name+" wins!");
            } else if (name2.equals("O")) {
                System.out.println(sum+" is odd..!");
                System.out.println("The computer wins!");
            }
        else {
                System.out.println(sum+" is odd..!");
                if (name2.equals("E")) {
                    System.out.println("The computer wins!");
                } else if (name2.equals("O")) {
                    System.out.println(name+" wins!");
                 }
            }
        }
        System.out.println("-----------------------------------------------------------");
    }
}

Aucun commentaire:

Enregistrer un commentaire