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...
CodePudding user response:
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;
}
CodePudding user response:
equals()
is the method of Object
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 it's 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.