0

This game I made has some problems on it that I can’t solve. It’s a game that you should always lose. But it only shows the first menu, and whatever you enter, nothing happens.

Can you help me fix it?

First menu I am talking about: First Menu

The code:

import javax.swing.JOptionPane; 

public class mainWork {  

public static void main(String[] args) { 
    int restart = 0; 
    String wannaplay = "no"; 
    
    int pc = 0;
    int user = 0;
    
    while(restart == 0) {
        String op = JOptionPane.showInputDialog("Which move you wanna do? \n(Rock, Paper, Scissors) \nUser:" + user + "\nPC:" + pc);
        String useropinion = op.toLowerCase(); 
        
        if(useropinion == "rock") { 
            pc = pc + 1; //pc skoruna bir eklemesi için
            JOptionPane.showMessageDialog(null, "PC has choosen Paper, you lost!");
            wannaplay = JOptionPane.showInputDialog("Do you wanna play again?"); 
            wannaplay = wannaplay.toLowerCase(); 
            
            if (wannaplay == "yes") { 
                restart = 0;
            } 
            else {
                restart = 1;
            }
            
        if(useropinion == "paper") {
            pc = pc + 1;
            JOptionPane.showMessageDialog(null, "PC has choosen Scissors, you lost!");
            wannaplay = JOptionPane.showInputDialog("Do you wanna play again?");
            wannaplay = wannaplay.toLowerCase();
                
            if (wannaplay == "yes") {
                restart = 0;
            } 
            else {
                restart = 1;
            }
        }
        
        if(useropinion == "rock") {
            pc = pc + 1;
            JOptionPane.showMessageDialog(null, "PC has choosen Paper, you lost!");
            wannaplay = JOptionPane.showInputDialog("Do you wanna play again?");
            wannaplay = wannaplay.toLowerCase();
                
            if (wannaplay == "yes") {
                restart = 0;
            } 
            else {
                restart = 1;
            }
         }
      }
   }
}}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • Thats not adding to your problem solution, but _please_: don't use `int`, where a `boolean` would be more than appropriate (and I'm talking of the _restart_ variable). – cyberbrain Mar 15 '22 at 20:52

1 Answers1

2

You have to compare strings using the .equals() method

So replace all the

useropinion == "something"

with

"something".equals(useropinion)

See: How do I compare strings in Java? for more info

The reason "foo".equals(variable) is because the string literal won't be null, while variable.equals("foo") can throw NullPointerException.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569