2014-09-18 1 views
-2

// **이 프로그램에 수학 임의 생성기를 배치하는 방법. 고마워요. **/수학 임의 생성기

// 어쨌든이 프로그램은 JOption 유틸리티를 사용하여 바위, 종이, 가위 게임에 관한 것입니다. // 플레이어 2에 Math Random Generator를 넣을 수 있습니까? 나는 그것을 어떻게 넣을 지 모르기 때문에. import javax.swing.JOptionPane; 클래스 activity13는 {

public static void main(String []args){ 

    int p1 = 0; 
    int p2 = 0; 

    String player1 = JOptionPane.showInputDialog("Select an option:\n(r) Rock\n(p) Paper\n(s) Scissor\nPlease input a keyword for player 1"); 
    String player2 = JOptionPane.showInputDialog("Select an option:\n(r) Rock\n(p) Paper\n(s) Scissor\nPlease input a keyword for player 2"); 

    String rock = "R"; 
    String paper = "P"; 
    String scissor = "S"; 


    if(player1.equalsIgnoreCase(rock)){ 

     p1 = 1; 

    } 
    if(player1.equalsIgnoreCase(paper)){ 

     p1 = 2; 

    } 
    if(player1.equalsIgnoreCase(scissor)){ 

     p1 = 3; 

    } 
    if(player2.equalsIgnoreCase(rock)){ 

     p2 = 1; 

    } 
    if(player2.equalsIgnoreCase(paper)){ 

     p2 = 2; 

    } 
    if(player2.equalsIgnoreCase(scissor)){ 

     p2 = 3; 

    } 
    if(p1 == p2){ 

     JOptionPane.showMessageDialog(null, "Draw", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
    if(p1 == 1 && p2 == 2){ 

     JOptionPane.showMessageDialog(null, "Player 2 Wins", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
    if(p1 == 1 && p2 == 3){ 

     JOptionPane.showMessageDialog(null, "Player 1 Wins", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
    if(p1 == 2 && p2 == 1){ 

     JOptionPane.showMessageDialog(null, "Player 1 Wins", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
    if(p1 == 2 && p2 == 3){ 

     JOptionPane.showMessageDialog(null, "Player 2 Wins", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
    if(p1 == 3 && p2 == 1){ 

     JOptionPane.showMessageDialog(null, "Player 2 Wins", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
    if(p1 == 3 && p2 == 2){ 

     JOptionPane.showMessageDialog(null, "Player 1 Wins", "Result", JOptionPane.INFORMATION_MESSAGE); 

    } 
} 

}

+0

Math.random()이 적합 할 것입니다 ... 나는 당신이 승리 한 모든 if와 잃는 if를 조합하여이 코드를 최적화 할 수 있다고 생각합니다. 운영자 –

답변

1

임의의 수는 java.util.Random의에 의해 발생 될 수 있습니다.

난수를 생성 할 준비를합니다. 즉, 시작 부분에 배치 할 코드입니다.

import java.util.Random; 

Random randomGenerator = new Random(); /* create intance of Random */ 

코드

변수 P2
p2 = randomGenerator.nextInt(3) + 1 /* nextInt(3) will return random number between 0 to 2, so add 1 */ 

매우 간단

1 내지 3 사이의 임의의 번호를 설정한다.

관련 문제