Runtime error- Program terminated
My program terminates for some reason. Its a rock-paper-scisors simulation. The termination takes place when I enter something in the first nextLine. If anybody could please help.
import java.util.*;
import java.math.*;
public class RockPapperScissors {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String comp, user;
comp=getComp();
System.out.println("Enter rock, paper, or scissors");
user=in.nextLine();
winner(comp, user);
}
public static String getComp(){
Ra开发者_C百科ndom rand=new Random();
String answer;
int ran=rand.nextInt(3);
if(ran==1)
answer="rock";
else if(ran==2)
answer="paper";
else
answer="scissors";
return answer;}
public static void winner(String com, String use){
if(com=="rock" && use=="rock")
System.out.println("Its a tie");
else if(com=="rock" && use=="paper")
System.out.println("You win!");
else if(com=="rock" && use=="scissors")
System.out.println("Computer wins, you FAIL");
else if(com=="paper" && use=="rock")
System.out.println("Computer wins, you FAIL");
else if(com=="paper" && use=="paper")
System.out.println("Its a tie");
else if(com=="paper" && use=="Scissors")
System.out.println("You win!");
else if(com=="scissors" && use=="rock")
System.out.println("You win");
else if(com=="scissors" && use=="paper")
System.out.println("Computer wins, you FAIL");
else if(com=="scissors" && use=="scissors")
System.out.println("Its a tie");}
}
For String comparison, use .equals()
rather than ==
.
Because strings are allocated to a common pool, "==" comparison will not work the way you intend it to. Use String's equals() method for comparing.
精彩评论