2012-10-23 3 views
0

나는 프로그래밍에 익숙하지 않고 간단한 바위 종이 가위 게임을 만들려고 노력해 왔습니다. 기본적으로 while 루프를 사용하여 사용자에게 재생할지 (계속할지) 묻습니다. 일단 그들이 더 이상 원하지 않으면, 프로그램은 총 게임 수, 승리 수, 손실 수 및 승률을 프린트해야합니다. 나는 전체 프로그램이 작동한다는 것을 제외하고 항상 그렇지 않은 경우에도 승률이 0.0 %라고 말합니다. 제로 오류로 인한 분열을 피하기 위해 이미 if 문을 사용했습니다. 런타임이나 컴파일러 오류가 발생하지 않아 뭔가를 놓치거나 논리 오류가 있습니다. 찾을 수 없습니다. 스캐너 사용을 계속하고 싶습니다.가위 바위 가위 게임

import java.util.Scanner; 

public class RockPaperScissors { 

/* 
* Program allows user to play Rock, Paper and Scissors as many times as desired by entering Y until they enter N. 
* Program will print amount of games played, amount lost, amount won and percentage won. 
* User must enter "Y", "N", "Rock", "Paper" or "Scissors" with correct capitalization and spelling. 
*/ 

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    int playerWins = 0; 
    int compWins = 0; 
    int gamesPlayed = 0; 

    while (true) { 
     System.out.println("Do you want to play Rock Paper Scissors (Y/N): "); 
     String play = input.nextLine(); 

     // user terminates game and program prints number of wins, losses and percentage of wins. 
     if (play.equals("N")) { 

      System.out.println("You played a total of " + gamesPlayed + " matches against the computer"); 
      System.out.println("The computer won " + compWins + " matches"); 
      System.out.println("You won " + playerWins + " matches"); 

      // 0% wins when no games are played. 
      if (gamesPlayed == 0) { 
       System.out.println("You won 0% of the time!"); 
       break; 

      } else if (gamesPlayed > 0) { 
       double totalWins = (int)(playerWins/gamesPlayed) * 100; 
       System.out.println("You won " + totalWins + "% of the time!"); 
       break; 
      } 

     } else if ((!play.equals("N")) && (!play.equals("Y"))) { 
      System.out.println("Invalid entry"); 
     } else { 

      System.out.println("Welcome to Rock, Paper and Scissors!"); 
      System.out.print("Select \"Paper\", \"Rock\" or \"Scissors\": "); 
      String decision = input.nextLine(); 
      System.out.println("Your selection: " + decision); 

      // random number generator producing integer values between 1 to 3 for computer's choices. 
      // 1 is for Rock, 2 is for Paper and 3 is for Scissors. 
      int num = (int)(Math.random() * (3-0) + 1); 

      switch (num) { 

       // Computer picks Rock 
       case 1: 
        if (decision.equals("Rock")) { 
        System.out.println("Tie, you and the computer selected rock"); 
        gamesPlayed++; 
       } else if (decision.equals("Paper")) { 
        System.out.println("You win, paper beats rock!"); 
        gamesPlayed++; 
        playerWins++; 
       } else if (decision.equals("Scissors")) { 
        System.out.println("Computer wins, rock beats scissors!"); 
        gamesPlayed++; 
        compWins++; 
       } else { 
        System.out.println(decision + " is not a valid input"); 
       } 
       break; 
       case 2: 
        // computer picks Paper 
        if (decision.equals("Rock")) { 
        System.out.println("Computer wins, rock beats paper!"); 
        gamesPlayed++; 
        compWins++; 
       } else if (decision.equals("Paper")) { 
        System.out.println("Tie, you and the computer selected paper"); 
        gamesPlayed++; 
       } else if (decision.equals("Scissors")) { 
        System.out.println("You win, scissors beats paper"); 
        gamesPlayed++; 
        playerWins++; 
       } else { 
        System.out.println(decision + " is not a valid input"); 
       } 
       break; 
       case 3: 
        // computer picks Scissors 
        if (decision.equals("Rock")) { 
        System.out.println("You win, rock beats scissors"); 
        gamesPlayed++; 
        playerWins++; 
       } else if (decision.equals("Paper")) { 
        System.out.println("Computer wins, scissors beats paper"); 
        gamesPlayed++; 
        compWins++; 
       } else if (decision.equals("Scissors")) { 
        System.out.println("Tie, you and the computer selected scissors"); 
        gamesPlayed++; 
       } else { 
        System.out.println(decision + " is not a valid input"); 
       } 
       break; 

      } 
     } 

    } 

} 

}

+4

오류가 여기에 있습니다 :'(INT) (playerWins/gamesPlayed) * 100;'. 힌트 : 정수 나누기. – nhahtdh

+0

또한 승 매트릭스를 사용하는 R-P-S의 enum 솔루션의 예를 들어 보겠습니다. [여기] (http://stackoverflow.com/a/8264256/522444) –

답변

5

문제는 double totalWins = (int)(playerWins/gamesPlayed) * 100;이다. playerWinsgamesPlayed은 둘 다 정수형 (특히 int 유형)이기 때문에 Java는 'Integer Division'을 수행하고 결과의 나누기 몫을 반환하고 나머지는 무시합니다. 가장에 그 라인을 변경 그래서이 일에서 그것을 방지하기 위해 :

double totalWins = (playerWins * 100.0)/gamesPlayed; 
//     /------------------\ 
// This converts the `playerWins` to a `double` and does the division as you expect 
+0

감사합니다.이 문제가 해결되었습니다! 나는 약간 혼란 스럽다. 왜 그 솔루션은 명시 적으로 2 개의 변수를 두 번 캐스팅하는 것과 반대되는 작업을 하는가? –

+0

두 번에 대한 명시 적 형변환의 문제점은 '0.8'과 같은 결과를 얻은 다음 소수점을 잃는 정수로 캐스팅하여'0'을 제공한다는 것입니다. 그런 다음 '0'을주는 '100'을 곱합니다. 여기서 이 메소드는'(800.0)/(10)'을 제공하고 Java는 나누기를 수행하며 이중 80.0을 리턴하며 이는 80을 제공하는 정수로 변환됩니다. – Lee

+0

이제 생각해 봅시다. 고맙습니다! –

관련 문제