2014-03-29 2 views
0

첫 번째 사항은 처음인데, 저는 여기에 새로운 것이므로이 내용이 질문에 대한 지침을 따르기를 바랍니다. 나는 다른 질문/스레드가 여기에 적용될 수 있다고 믿지 않는다. (적어도 그들은 나타나지 않았다.)스플릿 문자열 배열 [인덱스]> 상수가 거짓 일 때 True를 반환합니다.

어쨌든 저는 대학에서 C# 수업을 듣는 프로그래밍 초보자입니다. 내가하고있는 과제는 Split() 메소드와 관련이있다. 사용자에게 텍스트 상자의 이름과 볼링 점수를 묻고 임시 배열로 분할 한 다음 임시 배열에서 적절한 색인 값을 가져 와서 이름 및 점수 배열에 배치해야합니다. 최대 10 명의 플레이어를 처리해야하지만 그보다 적은 수의 플레이어에서만 작동합니다 (부분적으로 채워진 어레이).

높은 점수 + 그것을 가진 사람, 낮은 점수 + 그것을 가진 사람 및 평균 점수뿐만 아니라 모든 이름과 점수를 출력합니다. 배열에 들어가기 전에 0에서 300 사이의 입력 된 점수를 거부하고 싶습니다. 그러나 범위를 벗어난 값을 입력하고 디버그 할 때 /보다 작거나 같음이 true라고 말합니다. 분명히 내가 9001이나 -3 등을 점수로 입력하면 거부되기를 원할 것입니다. 여기에 코드의 일부가 있습니다. 사람이 왜 내가 '비슷한의 질문에 대답 작업뿐만 아니라이 일을하는 방법에 대한 예 (다른 심지어 리디렉션하지 않습니다에 대한 방법 또는 솔루션이있는 경우

 public void GetSplit(string _stg) 
     { 

     string[] tempArray; 

     //Split the temp array 
     tempArray = _stg.Split(); 

      //Professor said a for loop would be unnecessary since it's a GUI 

      //LOW = 300 

      if(score[index] <= LOW && score[index] >= 0) 
      {//this part here^^ is returning true when it should be false 

       //1st score is in the 2nd slot in tempArray 
       //if input is not between 0-300 and is NOT an integer, yell at them 
       if (!int.TryParse(tempArray[1], out score[index])) 
       { 
        MessageBox.Show(YELL_INT); 
        return; 
       } 

       bool status = (int.TryParse(tempArray[1], out score[index]) ? true :false); 
       //1st name is in 1st slot in tempArray 
       name[index++] = tempArray[0]; 


      } 
     } 

내가 놓친 것을 묻는 m), 그것은 굉장 할 것이다. 감사!

나는 날이를 추가하는 것이 필요하다 이유를 알고 있지만, 여기에 프로그램에서 모든 코드입니다하지 않습니다 코드보고에서 그래서

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Proj_08 
{ 
public partial class FrmMain : Form 
{ 

    private BowlingScores bs;//reference to bowlingscores class 

    /// <summary> 
    /// Purpose: Use the BowlingScores class to display names of players and scores 
    /// as well as high score + name, low score + name, and average score 
    /// </summary> 
    public FrmMain() 
    { 
     InitializeComponent(); 
    } 

    /// <summary> 
    /// Purpose: Initialize BowlingScores and _tempArray 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    private void Form1_Load(object sender, EventArgs e) 
    { 
     bs = new BowlingScores(); 
    } 

    /// <summary> 
    /// Purpose: Close out of program 
    /// </summary> 
    /// <param name="sender">Button Clear Click Event</param> 
    /// <param name="e">EventArgs Object</param> 
    public void MSpExit_Click(object sender, EventArgs e) 
    { 
     Close(); 
    } 

    /// <summary> 
    /// Purpose: Send the contents of the textbox to the GetScore method in BowlingScores class 
    /// </summary> 
    /// <param name="sender">Entry Enter Key Press Event</param> 
    /// <param name="e">KeyPressEventArgs Object</param> 
    private void TxtEntry_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if(e.KeyChar == (char)Keys.Enter) 
     { 


      bs.GetSplit(TxtEntry.Text); 
      TxtEntry.Text = string.Empty; 



     } 

    } 

    /// <summary> 
    /// Purpose: show everything in RichTextBox 
    /// </summary> 
    /// <param name="sender">Button Calc Click Event</param> 
    /// <param name="e">EventArgs Object</param> 
    public void BtnCalc_Click(object sender, EventArgs e) 
    { 
     //Output returned string from GetAll method 
     RTbOutput.Text = bs.GetAll(); 

    } 

    /// <summary> 
    /// Purpose: Clear the textboxes and reset all arrays and references and the index 
    /// </summary> 
    /// <param name="sender">Button Clear Click Event</param> 
    /// <param name="e">EventArgs Object</param> 
    private void BtnClear_Click(object sender, EventArgs e) 
    { 
     bs = new BowlingScores(); 

     TxtEntry.Text = string.Empty; 
     RTbOutput.Text = string.Empty; 


    } 


} 
//class BowlScores 
public class BowlingScores 
{ 
    private const int LOW = 300; 
    private const int ASIZE = 10; 
    private const string YELL_INT = "Invalid Score"; 
    private const string HEADER = "ERROR";//still have to add this 
    private int[] score; 
    private string[] name; 
    private int index; 

    /// <summary> 
    /// Purpose: Constructor for BowlingScores Class 
    /// </summary> 
    public BowlingScores() 
    { 
     index = 0; 
     score = new int[ASIZE]; 
     name = new string[ASIZE]; 



    } 

    /// <summary> 
    /// Purpose: Getter/Setter for name array 
    /// </summary> 
    public string[] Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 

    /// <summary> 
    /// Purpose: Getter/Setter for score array 
    /// </summary> 
    public int[] Score 
    { 
     get { return score; } 
     set { score = value; } 
    } 


    /// <summary> 
    /// Purpose: Capture text from textbox and split into name and score arrays 
    /// </summary> 
    /// <param name="_stg"></param> 
    public void GetSplit(string _stg) 
    { 
     //int index = 0; 
     string[] tempArray; 

     //Split the temp array 
     tempArray = _stg.Split(); 


      if(score[index] <= LOW && score[index] >= 0) 
      { 
       //1st score is in the 2nd slot in tempArray 
       //if input is not between 0-300 and is NOT an integer, yell at them 
       if (!int.TryParse(tempArray[1], out score[index])) 
       { 
        MessageBox.Show(YELL_INT, HEADER, MessageBoxButtons.OK, MessageBoxIcon.Error); 
        return; 
       } 

       bool status = (int.TryParse(tempArray[1], out score[index]) ? true : false); 
       //1st name is in 1st slot in tempArray 
       name[index++] = tempArray[0]; 
       //increment index to continue filling respective arrays 

      } 



    } 

    /// <summary> 
    /// Purpose: Calculate High, Low, Average 
    /// </summary> 
    /// <returns></returns> 
    public string CalcData() 
    { 
     int high = 0;//to figure high score 
     string holdHigh = ""; 
     int low = LOW;//to figure low score 
     string holdLow = ""; 
     double sum = 0.0; 
     double avg = 0.0; 
     double count = 0.0;//to calculate average, 

     // 
     for (int index = 0; index < score.Length && name[index] != null; index++) 
     { 
      //calculate high score 
      //if an entered score is greater than 0, replace high with that entered score 
      if (score[index] > high && score[index] <= LOW && score[index] >= 0) 
      { 
       high = score[index]; 
       holdHigh = name[index]; 
      } 

      //calculate the low score 
      //if an entered score is less than 300, replace low with that entered score 
      if (score[index] < low && score[index] <= LOW && score[index] >= 0) 
      { 
       low = score[index]; 
       holdLow = name[index]; 
      } 

      //calculate sum and average 
      if (score[index] <= LOW && score[index] >= 0) 
       sum += score[index]; 

       count = index + 1; 
       avg = (sum/count); 
     } 
     return string.Format("Congratulations {0}, you got the high score of {1}!\nBetter luck next time, {2}, you got the lowest score of {3}\nThe average score is {4:F2}", holdHigh, high, holdLow, low, avg); 

    } 

    /// <summary> 
    /// Purpose: Get all the names and scores and output them as a string 
    /// </summary> 
    /// <returns></returns> 
    public string GetAll() 
    { 
     string outputStg = ""; 

     //as long as entry isn't null and index is less than Length 
     for(int index = 0; index < score.Length && name[index] != null ; index++) 
     { 
      //if the score is above 300 or below 0, don't return those values 
      if (score[index] <= LOW && score[index] >= 0) 
      outputStg += name[index] + "\t\t" + score[index] + "\n"; 
     } 

     return outputStg += "\n" + CalcData(); 
    } 


} 
} 
+1

처럼 와우, 사람 ... 난 (10 분 이상!에 대한) 코드를 이해하기 위해 노력했습니다 맹세하지만 난 당신이 무슨 일을하는지 모르겠어요 .. 죄송합니다 – Buzinas

+0

그게 내가하고있는 일을 모르기 때문일 것입니다! 글쎄, 나는 내가하고있는 일을 안다고 생각하지만,이 경우에 무엇이 잘못되었는지를 모른다. 어쨌든 한 번 해봐 줘서 고마워! 이것은 제 첫 프로그래밍 수업이고 나는 여전히 모든 것에 매달려 있습니다. – Heckmaster9

답변

0

을 하나의 결함은 지금까지보고 아직 아무 것도 추가되지 않았 으면 score을 확인하고있는 것입니다! tempArray에 사용자가 입력 한 데이터가 포함되어있는 경우 먼저 확인해야합니다.

그래서

// I'm assuming your incoming string is formatted like "Name Score Name Score" 
// E.G. "Ryan 140 Tim 400" 
int result; 
string[] tempArray = _stg.Split(); 

if (int.TryParse(tempArray[1], out result)) 
{ 
    if (result <= LOW && result >= 0) 
     // within bounds, add it to score array, etc. 
} 
+0

그것은 훨씬 더 의미가 있습니다! 나는 당신의 충고를 좋은 결과로 사용할 수 있었고, 나는 그것을 올바른 것으로 표시하는 것을 잊었다. 감사! – Heckmaster9

관련 문제