据我所知,您想对重复号.txt文件中可用的每个数字进行计数。请在下面的代码中查找,我对您的代码进行了一些微调,例如文件路径和debug.log并删除不必要的变量。您可以看到input here和output here:如果发现可行,请投票并标记为答案。
我在Unity中输出当前代码时遇到问题。我正在使用输出文本字段来显示每个数字重复的数量。
曾经浏览过提要,但是没有得到我所需要的,所以现在我要问这个。
public int whatIndex,count;
public Text output;
public void Start()
{
string Random = "";
//reading the text file
string Duplicates = "duplicates.txt";
string Duplicates_Path = Application.dataPath + "/Text_Files/" + Duplicates;
string[] Numbers = File.ReadAllLines(Duplicates_Path);
foreach(string number in Numbers)
{
Random += number;
}
output.text = Random + "\n";
//array for text
for (whatIndex = 0; whatIndex < Duplicates.Length; whatIndex++)
{
Debug.Log(Numbers[whatIndex] + "\n");
Debug.Log("The number " + Numbers[whatIndex].ToString() + " appears " + count +
" times(s)");
}
}
我不确定,您想要实现什么,但是我想您的代码有一些问题(请参阅后面的代码)。
首先,您可以尝试使用此代码来获得一个解决方案的想法,该解决方案是使用System.Collections.Generic中的Dictionary读取文本文件后获取重复项和重复项的数量:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// String array with duplicates
string[] Numbers = {"1","1", "2", "6","1","7","1","7","8","3"};
Dictionary<string, int> KeyNumbersValueCount = new Dictionary<string, int>();
foreach(string number in Numbers)
{
if(KeyNumbersValueCount.ContainsKey(number))
KeyNumbersValueCount[number] += 1;
else
KeyNumbersValueCount.Add(number, 1);
}
foreach(var NumberAndCount in KeyNumbersValueCount)
Console.WriteLine("The number " + NumberAndCount.Key + " appears " +
NumberAndCount.Value + " times(s)");
}
}
您需要数吗?已初始化但从未使用过]]
如果不需要“ whatIndex”,那么您也可以在for循环中将其初始化:
for (int whatIndex = 0; whatIndex < Duplicates.Length; whatIndex++)
{
// do s.th.
}
您正在尝试遍历字符串“ Duplicates”的长度,即“ duplicates.txt”,因此长度为14。我想您要遍历文件中的字符串。] >
在您的情况下,Random实际上没有功能。如果您只想打印,也可以使用File.ReadAllText代替File.ReadAllLines并将其移交给output.text。 See Microsoft Refs。
据我所知,您想对重复号.txt文件中可用的每个数字进行计数。请在下面的代码中查找,我对您的代码进行了一些微调,例如文件路径和debug.log并删除不必要的变量。您可以看到input here和output here:如果发现可行,请投票并标记为答案。
public void Start()
{
Dictionary<int, int> numberCount = new Dictionary<int, int>();
//reading the text file
string Duplicates = "duplicates.txt";
string Duplicates_Path = Environment.CurrentDirectory + "\\Text_Files\\" + Duplicates;
string[] Numbers = File.ReadAllLines(Duplicates_Path);
foreach (string number in Numbers)
{
int temp = int.Parse(number);
if (numberCount.ContainsKey(temp))
{
numberCount[temp] = numberCount[temp] + 1;
}
else
{
numberCount[temp] = 1;
}
}
//array for text
foreach(KeyValuePair<int,int> item in numberCount)
{
Console.WriteLine("The number " + item.Key.ToString() + " appears " + item.Value.ToString() +
" times(s)");
}
}
据我所知,您想对重复号.txt文件中可用的每个数字进行计数。请在下面的代码中查找,我对您的代码进行了一些微调,例如文件路径和debug.log并删除不必要的变量。您可以看到input here和output here:如果发现可行,请投票并标记为答案。