What is the correct way to write this if else statement?

Looking for assistance with a program I've been working on. In this program, there are three dice and three players. Player 1 rolls die 1, player 2 rolls die 2, and player 3 rolls die 3. The goal is to determine the winner based on who gets the highest number (between 1-6). However, I'm struggling to write an if-else statement that accurately displays the winner. Here's some code I've attempted:


    if (randomNumber1 > randomNumber2 || randomNumber3) {
        document.querySelector("h1").innerHTML = "Player 1 Wins! 🚩";
    }
    else if (randomNumber2 > randomNumber1 || randomNumber3) {
        document.querySelector("h1").innerHTML = "Player 2 Wins! 🚩";
    }
    else if (randomNumber3 > randomNumber1 || randomNumber2) {
        document.querySelector("h1").innerHTML = "Player 3 Wins! 🚩";
    }
    else {
        document.querySelector("h1").innerHTML = "No Winner!";
    }

I've encountered issues where the program incorrectly declares the winner. For instance, when player 1 has a 5 and player 3 has a 6, it still claims player 1 as the winner. It seems like my if-else logic is off. Can anyone provide guidance on how to correct this? I'm relatively new to coding and have been grappling with this problem all day. To assist me better, please show me the corrected code formatting. Feel free to modify the code I've already written.

Answer â„–1

Give this a shot

if (num1 > num2 && num1 > num3) {
    document.querySelector("h1").innerHTML = "Player 1 is the Winner! 🚩";
    }
    else if (num2 > num1 && num2 > num3) {
    document.querySelector("h1").innerHTML = "Player 2 claims Victory! 🚩";
    }
    else if (num3 > num1 && num3 > num2) {
    document.querySelector("h1").innerHTML = "Player 3 emerges triumphant! 🚩";
    }
    else {
    document.querySelector("h1").innerHTML = "No one prevails!";
    }

The issue was with your if statement. The && doesn't mean that the first comparison will be made against both of the other numbers, it means that both comparisons need to be true for the if statement to execute.

Also remember to check if two or all players have the same value which ends up being the highest number.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

Tips on eliminating the letter 'X' from a text/search input field in HTML

There are various solutions available for removing the "X" from an input field in IE 10+ browsers. I have tried multiple approaches without success. For example, I have referenced: ans 1 ans 2 ans 3 Despite implementing all of these solutions, I still ...

Transforming a namespaced function into an asynchronous operation by utilizing setTimeout

Looking for help with making a function that uses namespaces asynchronous. The function is currently being called on the click of a button. var ns = { somemfunc: function (data) { alert("hello"); } } Edit: ...

Assignments made to the 'toLoadNumber' variable within the React Hook useEffect will be reset after every re-render

I encountered an issue in the console related to the code snippet below: export const Contact = () => { useEffect(() => { // Code inside this block runs when the component mounts. return () => { // Code inside this block runs when the component ...

(discovered: [object Promise]) utilizing Material UI and DexieJS

Exploring DexieJS and Material UI for the first time has been quite a learning experience, so I may have overlooked a crucial aspect. Here is a glimpse of my code: Subscreen.tsx const [fightersArray, setFightersArray] = useState<FighterEntity[]>([]) ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

How can you continuously calculate and show the total quantity of items in a list?

Currently, I have lists set up in my sidebar and I'm looking to include a label displaying the number of items within each list. To provide a better understanding of what I'm aiming for, I've put together a JSFiddle demonstration at the fol ...

Transitioning from GeometryUtils.merge() to geometry.merge()

When upgrading from r66 to r67, a message pops up stating: DEPRECATED: GeometryUtils's .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead. The transition doesn't seem straightforward beca ...

How to retrieve response data in React from outside the axios scope

Starting my journey in developing a React application for the first time! I plan to populate a table using the response from Axios. However, I'm wondering if it's possible to access the response from Axios in the global scope rather than within ...

I am looking for a specific task to be carried out, without any need for returning a value or any additional items

I am trying to remove an element from the canvas using Selenium. The command I am currently using is "window.app.design.internalLayer().find('.deletebutton').fire('click')". Despite my efforts, this command does not seem to be working a ...

Deactivate DropDownList within Update Panel with JQuery

Below is the Update Panel that I am working on: <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="d ...

When using the Infinite Scroll React component, only a single new set of objects is loaded as you scroll down, and the loading

My React component is designed to load 6 images at a time as the page is scrolled down, creating an infinite scroll effect similar to what YouTube and Reddit now use. Currently, when the page loads, it shows the initial 6 images correctly. However, as I c ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Executing a child function from the parent component in React 16

Ever since I upgraded to react 16, I've been encountering null in my console.log(this.child) The Main Component import EditReview from './partials/editReview' class VenueDetails extends Component { constructor(props) { super(props) ...

Creating a unique custom bottom position for the popover and ensuring it is fixed while allowing it to expand

Creating a customized popover similar to Bootstrap's popover, I have successfully implemented popovers in all directions except for the top direction. My challenge lies in fixing the popover at the bottom just above the button that triggers it, and en ...

Extracting information from the responseText of an XMLHttpRequest

Using AJAX, I am retrieving some data that I need to manipulate after the AJAX call completes. However, I am facing an issue where I can't seem to manipulate the response. Here is the code snippet: function testAjax() { direc = "co ...

Enhance Your Forms with Bootstrap 4 Validation Using JavaScript/jQuery

Exploring the world of web development, I have ventured into setting up a practice form to delve into the art of form validation. Utilizing Bootstrap's documentation for Custom Styles ensures compatibility with screen readers and presents a consistent ...

Utilizing an Async API call from a separate page and passing it as a component input

I recently set up an asynchronous API fetch in one of my .JS files and then invoked it from another JS file to output the result using console.log. (Is there a more efficient method for achieving this?) Now, my aim is to utilize the fields of the response ...

Tips for linking node objects to node identifiers in a d3 tutorial?

Currently, I'm going through a tutorial that can be found at- However, there's a particular section in the tutorial that has me puzzled. "In conclusion, we link node ids to node objects and then substitute the source and target values in our li ...