我正在撰寫一個簡單的控制臺筆記應用程式,并且在“foreach”功能方面遇到了一些問題。當我輸入“查看”時,筆記應該按順序顯示,但對于每個筆記,我得到“0”,而不是“0”“1”“2”。

using System;
using System.Collections.Generic;
namespace note_app_console
{
class Program
{
static void Main(string[] args)
{
List <String> notes = new List<string>();
Console.WriteLine("Notes");
int userInput;
//main loop
do
{
string addNote;
//selecting action from menu
userInput = Convert.ToInt32(Console.ReadLine());
switch (userInput)
{
case 1:
Console.WriteLine("Enter the note content: ");
addNote = Console.ReadLine();
notes.Add(addNote);
Console.WriteLine("Note added.");
break;
case 2:
Console.WriteLine("Your notes: ");
foreach (string i in notes)
{
int indexNote = i.IndexOf(i);
Console.WriteLine($"{Convert.ToString(indexNote)}. {i}");
}
break;
}
} while (userInput != 4);
}
}
}
uj5u.com熱心網友回復:
這里的三個選項
使用
notes.IndexOf()foreach (string item in notes) { int indexNote = notes.IndexOf(item); Console.WriteLine($"{indexNote}. {item}"); }使用計數器
int counter = 0; foreach (string item in notes) { Console.WriteLine($"{counter}. {item}"); counter ; }使用 for 回圈
for(int i=0; i<notes.Count; i ) { Console.WriteLine($"{i}. {notes[i]}"); }
請注意,無需在WriteLine()陳述句中將整數轉換為字串,因為字串插值會自動執行此操作。
uj5u.com熱心網友回復:
首先,您的變數名稱令人困惑。將 更改foreach (string i in notes)為foreach (string note in notes)。
其次,在notes陣列中尋找當前音符的索引,因此將其i.IndexOf(i)改為notes.IndexOf(note)
foreach (string note in notes)
{
int idx = notes.IndexOf(note);
Console.WriteLine($"{Convert.ToString(idx)}. {note}");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348136.html
上一篇:在Blazor中實作拖放(drag and drop)
下一篇:在特定時間啟動任務
