Why is my c# code not working? -
i have made console program in c# to-do task manager.
not work when code reached:
using system; using system.collections.generic; using system.io; using system.linq; using system.text; using system.threading.tasks; namespace to_do_list { class program { static void main(string[] args) { string path = @"c:\todotask.txt"; console.writeline("to-do program"); while (true) { if (console.readline() == "exit") { environment.exit(0); } if (console.readline() == "add") { console.writeline("please write task , press enter"); string task = console.readline(); console.writeline("task added"); try { streamwriter sw = new streamwriter(path); sw.writeline(task); } catch { console.foregroundcolor = consolecolor.red; console.writeline("error: not write task file"); console.resetcolor(); } } if (console.readline() == "show") { try { console.writeline("tasks:"); streamreader sr = new streamreader(path); if (sr.readtoend() != "") { console.writeline(sr.readtoend()); } else { console.writeline("no tasks left"); } } catch { console.foregroundcolor = consolecolor.red; console.writeline("error: not read tasks file"); console.resetcolor(); } } if (console.readline() == "help") { console.writeline("write 'add' add new task"); console.writeline("write 'show' see current tasks"); console.writeline("write 'exit' exit program"); } } } } }
i new programming , can't find error. when write add, show or exit, or nothing happens. thanks.
one problem keep calling console.readline()
every comparison. means you're checking a new input user every time.
instead, need call console.readline()
once, store result in variable, , compare against of possible matches. also, using switch
statement make code simpler.
while (true) { var input = console.readline(); switch (input) { case "exit": environment.exit(0); break; case "add": // ... break; // ... default: console.writeline("invalid input"); break; } }
Comments
Post a Comment