2014-09-29 2 views
-2

내 프로그램에서 스택 오류가 발생합니다. 함수와 속성을 가진 클래스가 있는데, 액세스 할 수 있으려면 winform 텍스트 상자, 체크 상자 등으로 부분 클래스가 필요합니다. 내가 잘 만들면하지만 런타임 오류가 발생합니다. 그것은 내가 가지고있는 기본 생성자를 가리키며, 어디에서 Visual Studio가 스택 오버플로를 요청하는지 winform에서 사용하고 있습니다. 코드 :스택 오버플로 오류. winforms 사용하기

public class TeamCreator:Form 
    { 
     //fields 
     public string[] players=new string[12]; 
     public int[] points=new int[12]; 
     public int currentPlayerScore=0; 
     public TeamCreator()//default constructor 
     { 
      for (int i = 0; i < 11; i++) 
      { 
       this.players[i] = ""; 
       this.points[i] = 0; 
      } 

     } 
     public TeamCreator(string[] teammates,int[] scores)//construct Team object with user input 
     { 
      this.players = teammates; 
      this.points = scores; 

     } 
     public void setTeammates(string player,int index)//set players array 
     { 
      this.players[index] = player; 
     } 
     public void setPoints(int[] scoreList)//set points array 
     { 

       this.points = scoreList; 
     } 
     public void setPlayerScore(int playerScore,int playerNum)//sets a specific player's score 
     { 
      this.points[playerNum] = playerScore; 

     } 
     public int[] getPoints()//obtain array of points 
     { 
      int[] listOfPoints=new int[12]; 
      int i; 
      for(i=0;i<11;i++) 
      { 
       listOfPoints[i]=this.points[i]; 
      } 
      return listOfPoints; 
     } 
     public int totalPoints()//gets total points 
     { 
      int total=0; 
      for(int i=0;i<11;i++) 
      { 
       total = this.points[i] + total; 
      } 
      return total; 
     } 
     public double meanPoints()//returns mean or average of total points 
     { 
      int total = this.totalPoints(); 
      int mean = total/11; 
      return mean; 
     } 
    } 
} 

       //winform code 
       namespace TeamClass 
{ 
    public partial class TeamClass:TeamCreator 
    { 
     public int indexOn = 0; 
     public int current = 0; 
     public TeamCreator newTeam = new TeamCreator(); 
     public TeamClass() 
     { 
      InitializeComponent(); 
     } 

     private void playerInput_MouseLeave(object sender, EventArgs e)//adds players to players array and to list 
     { 
      string playerName = playerInput.Text; 
      newTeam.setTeammates(playerName,this.indexOn); 
      playerList.Items.Add(playerName); 
      indexOn++; 
     } 
     TeamClass reopen = new TeamClass(); 
     private void restart_CheckedChanged(object sender, EventArgs e)//allows user to restart program and make a new team 
     { 
      this.Visible = false; 
      reopen.Show(); 

     } 

     private void playerScoreDisplay_CheckedChanged(object sender, EventArgs e)//displays currently selected player when checked 
     { 
      string currentPlayerSelected = newTeam.players[current]; 
      MessageBox.Show("The current player selected is " + currentPlayerSelected + ".", "Current Player", MessageBoxButtons.OK); 
     } 

     private void playerList_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      this.current = playerList.SelectedIndex; 


     } 

     private void scoreInput_MouseLeave(object sender, EventArgs e)//gets player score 
     { 
      int currentScore; 

      if (!Int32.TryParse(scoreInput.Text, out currentScore)) 
      { 
       //tell user we can't parse the amount 
       if (MessageBox.Show("Text did not parse to an integer, please try again", "Invalid Argument", MessageBoxButtons.RetryCancel) == System.Windows.Forms.DialogResult.Cancel) 
       { 
        // leave method if they don't want to try again 
        return; 
       } 
       else 
       { 
        //set the focus on the control so user can fix error 
        scoreInput.Focus(); 
        //As a convenience select all text 
        scoreInput.SelectAll(); 
        //exit method 
        return; 
       } 
      } 

       newTeam.setPlayerScore(currentScore, current); 


     } 

     private void scoreInput_KeyPress(object sender, KeyPressEventArgs e)//makes sure numbers are being entered correctly for score 
     { 
      //only accept negative sign in first position 
      if ((e.KeyChar == '-') && ((sender as TextBox).Text.Length == 0)) 
      { 
       if ((sender as TextBox).Text.Contains("-")) 
        e.Handled = true; 
      } 
      //Only accept numbers, one decimal, one negative sign (-) and the backspace 
      else if (!char.IsDigit(e.KeyChar) && !char.IsPunctuation(e.KeyChar) && !(e.KeyChar == 0x08)) 
      { 
       e.Handled = true; 
      } 
     } 

     private void totalPointsDisplay_CheckedChanged(object sender, EventArgs e)//displays total points when checked 
     { 
      int total=newTeam.totalPoints(); 
      MessageBox.Show("The total points for the team is " + total + ".", "Total Points", MessageBoxButtons.OK); 
     } 

     private void MeanPointsDisplay_CheckedChanged(object sender, EventArgs e)//displays mean points when checked 
     { 
      double avg=newTeam.meanPoints(); 
      MessageBox.Show("The mean points for the team is " + avg + ".", "Mean Points", MessageBoxButtons.OK); 

     } 

    } 
    } 

나는이 오류가 어떻게이 많이 주시면 감사하겠습니다 해결하는 방법입니다 이유에 어떤 도움. 나는 C#에 다소 익숙하다. 그래서 문제가 무엇인지 확신 할 수 없다.

+1

시작하려면 항상 루프. – Blorgbeard

답변

2

예외적으로 많은 것을 알 수없는 경우가 있습니다. 대신에 도움이 스택 트레이스, 당신은 같은 메시지가 표시됩니다

현재의 thread가 스택 오버 플로우 상태에 있기 때문에

이 주위에 몇 가지 방법이 있습니다 식을 계산할 수 없습니다 당신이 할 경우 "stackoverflow exception stack trace"로 검색하십시오.

근원 문제는 거의 항상 재귀이지만, 자체를 호출하는 무언가 또는 루프에서 서로를 호출하는 두 개 또는 세 개의 메소드를 찾습니다.

코드를 빠르게 스캔 한 후 거의 즉시 발견했습니다 (다른 코드도있을 수 있음). TeamClass을 인스턴스화 할 때마다 다른 인스턴스를 만들고 다른 인스턴스를 만들고 계속해서 만듭니다.

public partial class TeamClass:TeamCreator 
{ 
    ... 
    TeamClass reopen = new TeamClass(); 
    ... 
+0

고맙습니다. 지금 제 프로그램이 제대로 작동하고 있습니다. – arisonu123

0

모든 코드에서 배열의 처음 11 개 요소를 사용하는 이유는 무엇입니까? 12 개의 요소와 배열을 정의하지만 스택 추적을 포함하여 전체 예외 메시지,보고에 의해 11 요소

public string[] players=new string[12]; 
     public int[] points=new int[12]; 
     public int currentPlayerScore=0; 
     public TeamCreator()//default constructor 
     { 
      here why you loop to 11 it suppose to be 12 or the array.Length 
      for (int i = 0; i < 11; i++) 
      { 
       this.players[i] = ""; 
       this.points[i] = 0; 
      } 
+0

배열이 0에서 1까지 크기가 작아서 0-11에서 나왔다고 생각했습니다. 내가 실제로 그들 모두에 접근하지 못한다면, 12보다 적거나 11보다 적거나 같을 것입니다. – arisonu123

+0

예 i <= 11로 수정됩니다. 배열의 크기는 12이며, i가 11보다 작 으면 조건은 루프를 중지하므로 배열의 마지막 요소는 무시됩니다. –

+0

한 가지 더 TeamClass reopen = new TeamClass(); 은 메서드에서 전용이어야 함 private void restart_CheckedChanged (개체 보낸 사람, EventArgs e) –