[英]How to Display Array Values using Nested For loops?
在我們開始之前,我是編程和 C# 語言的新手,所以請耐心等待。 我遇到的問題是像這樣在彼此面前顯示兩個單獨的數組值:
整數類型:sbyte、byte、short、ushort
Real 浮點類型:float、double
我試過的代碼是:
string[] VariableTypes = { "Integer Type", "Real Floating Point Types" };
string[] IntergerTypes = { "sbyte", "byte", "short", "ushort" };
for (int i = 0; i <= VariableTypes.Length - 1; i++)
{
for(int j=0; j<=IntergerTypes.Length - 1; j++)
{
Console.Write(IntergerTypes[j] + " ");
}
Console.WriteLine(VariableTypes[i] + " : ");
}
我得到的輸出:
sbyte byte short ushort 整數類型:
sbyte byte short ushort 實數浮點類型:
您需要另一個數組來保存要與Real Floating Point Types
相關的值,然后有條件地檢查變量類型以查看與之關聯的整數類型。
string[] VariableTypes = { "Integer Type", "Real Floating Point Types" };
string[] FloatingPointTypes = { "float", "double" };
string[] IntergerTypes = { "sbyte", "byte", "short", "ushort" };
for (int i = 0; i <= VariableTypes.Length - 1; i++)
{
Console.WriteLine(VariableTypes[i] + " : ");
if(VariableTypes[i] == "Integer Type")
{
for(int j=0; j<=IntergerTypes.Length - 1; j++)
{
Console.Write(IntergerTypes[j] + ", ");
}
}
else
{
for(int j=0; j<=FloatingPointTypes.Length - 1; j++)
{
Console.Write(FloatingPointTypes[j] + ", ");
}
}
}
在我看來,如果您只想要一種實現上述輸出的方法,那么在沒有嵌套循環的情況下這樣做會更干凈:
string[] FloatingPointTypes = { "float", "double" };
string[] IntergerTypes = { "sbyte", "byte", "short", "ushort" };
Console.WriteLine("Integer Type: " + string.Join(", ", IntergerTypes));
Console.WriteLine("Real Floating Point Types: " + string.Join(", ", FloatingPointTypes));
另外,您可以利用一個類使您的工作更簡化。 請參閱以下內容:
public class VariableType
{
public string Name { get; set; }
public List<string> DataTypes { get; set; }
}
並通過以下步驟使用該類來實現所需的結果:
var variableTypes = new List<VariableType>
{
new VariableType
{
Name = "Integer Types",
DataTypes = new List<string>{ "sbyte", "byte", "short", "ushort" }
},
new VariableType
{
Name = "Real Floating Point Types",
DataTypes = new List<string>{ "float", "double" }
}
};
foreach(var variableType in variableTypes)
{
Console.WriteLine(variableType.Name + " : " + string.Join(", ", variableType.DataTypes));
}
string[] VariableTypes = {
"Integer Type", "Real Floating Point Types"
};
string[][] NumberTypes = {
new string[] { "sbyte", "byte", "short", "ushort" },
new string[] { "float", "double" }
};
for (int i = 0; i < VariableTypes.Length; i++)
{
Console.Write(VariableTypes[i] + " : ");
for(int j = 0; j < NumberTypes[i].Length; j++)
{
Console.Write(NumberTypes[i][j] + " ");
}
Console.WriteLine();
}
這是實現此目的的簡短方法:
string[] VariableTypes = { "Integer Types", "Real Floating Point Types" };
string[] IntegerTypes = { "sbyte", "byte", "short", "ushort" };
string[] RealFloatingPointTypes = { "float", "double" };
Console.WriteLine(String.Concat(VariableTypes[0], " : ", String.Join(", ", IntegerTypes)));
Console.WriteLine(String.Concat(VariableTypes[1], " : ", String.Join(", ", RealFloatingPointTypes)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.