简体   繁体   中英

Split String Array[index] > constant returning True when it should be false

First things first, I'm brand new here and I'm hoping that this adheres to your guidelines for questions. I don't believe other questions/threads here would be applicable (at least they didn't appear to be).

Anyways, I'm a programming novice taking a C# class in college. The assignment I'm working on has to do with the Split() method. I'm supposed to ask the user for names and (bowling) scores in a textbox, split it into a temporary array, then take the appropriate index values from the temporary Array and place them in Name and Score arrays. It should handle up to 10 players, but it should work for fewer than that (partially filled array).

It will calculate and output the high score + who has it, the low score + who has it, and the average score, as well as outputting all the names and scores. I want to reject any entered scores that aren't between 0 and 300 before they enter the array, but when I enter a value outside of that range and debug, it says that the greater than/less than/ equal to is true. Obviously, if I enter 9001 or -3 etc. as a score I'd want it to be rejected. Here is that part of the code.

        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];


            }
         }

If anyone has a solution as to how or why this isn't working, as well as an example on how to get it to work (even a redirect to another answered question that's similar to the one I'm asking that I missed), that'd awesome. Thanks!

I don't know why it would be necessary for me to add this, but here's all of the code from the program:

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();
    }


}
}

So from looking at your code, one flaw I saw so far is that you are checking score when nothing has been added to it yet! if your tempArray contains the data the user has input, you should be checking that first.

So like

// 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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM