using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//My Baseball application named BatStat
namespace BatStat
{
class Program
{
static void Main()
{
//My declared variables that hold the user input in memory
string teamName;
string[] playerName = new string[9];
string[] playerPosition = new string[9];
int[] atBats = new int[9];
int[] hits = new int[9];
float teamBA = 0;
//Begin program by requesting user to enter team name value
WriteLine("Welcome to Bat Stat, enter team name");
teamName = Console.ReadLine();
//Traverse all arrays and accumalate values from user input
for (int i = 0; i < playerName.Length; i++)
{
WriteLine("Enter players name");
playerName[i] = ReadLine();
WriteLine("Enter Players Position");
playerPosition[i] = ReadLine();
WriteLine("Enter Players at bats");
atBats[i] = Convert.ToInt32(ReadLine());
WriteLine("Enter Players hits");
hits[i] = Convert.ToInt32(ReadLine());
}
//Display top row menu for Bat Stat table
WriteLine("{0, -10}{1, -10}{2, -5}{3, -5}{4, -5}{5, -5}", "Team", "Player", "Pos", "AB", "H", "BA");
//for loop to traverse the arrays and display user input data
for (int x = 0; x < playerName.Length; ++x)
{
float playerBA = (float) hits[x] / atBats[x];
WriteLine("{0, -10}{1, -10}{2, -5}{3, -5}{4, -5}{5, -4}", teamName, playerName[x], playerPosition[x], atBats[x].ToString("d"), hits[x].ToString("d"), playerBA.ToString("F3"));
}
{
//Display the team batting average
float teamBA = hits[] / atBats[];
WriteLine("The batting average for the {0} is {1}", teamName, teamBA.ToString("F3"));
}
}
}
}
如何通过使用 teamBA 变量来保存命中/atBats 的值来输出最终 WriteLine 方法的字符串? Visual Studio 表示 teamBA 未在此范围内声明。两个数组 hit 和 atBats 正在注册语法错误的错误;预期值。除了最后一个 WriteLine 方法之外,一切正常。
最佳答案
在
for (int x = 0; x < playerName.Length; ++x)
{
float playerBA = (float) hits[x] / atBats[x];
WriteLine("{0, -10}{1, -10}{2, -5}{3, -5}{4, -5}{5, -4}", teamName, playerName[x], playerPosition[x], atBats[x].ToString("d"), hits[x].ToString("d"), playerBA.ToString("F3"));
}
{
//Display the team batting average
float teamBA = hits[] / atBats[];
WriteLine("The batting average for the {0} is {1}", teamName, teamBA.ToString("F3"));
}
- 第二个 block 的用途是什么,它不在您的
for
循环中。 - 您已经重新声明了第二次
float teamBA
,第一次位于您方法的顶部 hits[]/atBats[]
没有任何意义,你不能分割数组。您必须放置一个类似hits[2]/atBats[2]
的索引
关于c# - 在 C# 中,我试图显示上一个 WriteLine 方法中的文本字符串。出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60518339/