我正在尝试将字符串从一个方法传递给我的Main
方法。
该程序是一个C#控制台应用程序。它应该让用户输入他的名字,姓氏和出生地。然后它应该反转每个并再次输出它们。 (例如Bob Tabor America - > boB robaT aciremA)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelperMethods
{
class Program
{
static void Main(string[] args)
{
GetString();
DisplayResult(ReverseString(input));
}
private static string GetString()
{
Console.WriteLine("The Name Game");
Console.Write("What's your first name? ");
string firstName = Console.ReadLine();
Console.Write("What's your last name? ");
string lastName = Console.ReadLine();
Console.Write("In what city were you born? ");
string birthPlace = Console.ReadLine();
string input = firstName + " " + lastName + " " + birthPlace;
return input;
}
private static string ReverseString(string message)
{
char[] messageArray = message.ToCharArray();
Array.Reverse(messageArray);
return String.Concat(messageArray);
}
private static void DisplayResult(string result)
{
Console.Write("Results: " + result);
}
}
}
请注意我是如何尝试将GetString()
的字符串输入传递给Main
方法。
给出的错误是:
名称'输入'在当前上下文中不存在
我该怎么办?
答案 0 :(得分:1)
您需要先存储input
:
static void Main(string[] args)
{
var input = GetString();
DisplayResult(ReverseString(input));
}
答案 1 :(得分:1)
namespace HelperMethods
{
class Program
{
static void Main(string[] args)
{
var input = GetString();
DisplayResult(ReverseString(input));
}
private static string GetString()
{
Console.WriteLine("The Name Game");
Console.Write("What's your first name? ");
string firstName = Console.ReadLine();
Console.Write("What's your last name? ");
string lastName = Console.ReadLine();
Console.Write("In what city were you born? ");
string birthPlace = Console.ReadLine();
string input = firstName + " " + lastName + " " + birthPlace;
return input;
}
private static string ReverseString(string message)
{
char[] messageArray = message.ToCharArray();
Array.Reverse(messageArray);
return String.Concat(messageArray);
}
private static void DisplayResult(string result)
{
Console.Write("Results: " + result);
}
}
}
答案 2 :(得分:0)
string result = GetString();
DisplayResult(ReverseString(result));
答案 3 :(得分:0)
试试这个:
static void Main(string[] args)
{
string input = GetString();
DisplayResult(ReverseString(input));
}
答案 4 :(得分:0)
简单地
static void Main(string[] args)
{
DisplayResult(ReverseString(GetString()));
}
但是,对于您期望的输出,请在print / concat之前反转每个单词。
例如
using System;
public static class Program {
public static void Main(string[] args) {
Console.WriteLine("The Name Game");
Console.Write("What's your first name? ");
var firstName = Console.ReadLine().Reverse();
Console.Write("What's your last name? ");
var lastName = Console.ReadLine().Reverse();
Console.Write("In what city were you born? ");
var birthPlace = Console.ReadLine().Reverse();
Console.Write("Result: {0} {1} {2}", firstName, lastName, birthPlace);
}
public static string Reverse(this string s) {
var arr = s.ToCharArray();
Array.Reverse(arr);
return new string (arr);
}
}
输出
Result: boB robaT aciremA