简体   繁体   中英

How to compare two methods in Java

Am trying to compare two methods but am getting this error:

cannot invoke equals(void) on primitive type void

Code:

package rockpaper;

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


public class game { 
  public static void main(String[] args) {
   String rock="r";
   String paper="p";
   String scissors="s";
   userInput();
   compInput();


if(userInput().equals(compInput())){//this is where the error is//
 
   }
  }
  public static void userInput(){
  Scanner put=new Scanner(System.in);
    String user;
    System.out.println("enter your move....");
    user=put.nextLine();
    if(user.equals("r")){
      System.out.println("your move is rock");
    }
    if(user.equals("p")){
    System.out.println("your move is paper");
  }
  if(user.equals("s")){
    System.out.println("your move is scissors");
  }
 }
 public static void compInput(){
   Random rand=new Random();
   int comp;
   String system;
   comp=rand.nextInt(3);
   if(comp==1){
   V system="rock";
   }
   if(comp==2){
     system="paper";
   }
   if(comp==3){
     system="scissors";
   }
 }
}

the above code is for rock paper scissors game, I've tried to compare using the normal way but there is an error which i know why,it because what am trying to compare isn't in the main method...

You don't want to compare methods, what you want to do, is to compare values returned by those methods.

to do that, you need to change return type for your method, and add return statement

public static String compInput(){
   //Existing body   
   return system;
   
 }

If the method returns void , it means that you can't get the value because it doesn't exist. The method doesn't return a value. Even if it's a primitive type can't be compared. Thus you can't use it in expressions to evaluate its value. It's notObject , so you can't invoke a method using dot operator.

equals() is the method ofObject and it's used to compare objects, not methods. When creating some classes from that objects are instantiated this method is usually overridden to make comparing objects more relevant to its data that it holds in the fields.

For your better experience using objects try to create some POJO and return it from methods.

Also use DRY principle when writing a code. Because if you want to invoke some methods don't do multiple times if it is not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM