2015-01-19 2 views
0

그래서 Movie 메서드를 요청하고 문자열과 정수로 이름을 받아들이도록 요청하는 질문이 있습니다 (분 단위의 시간을 나타냄). 따라서 정수없이이 메서드를 호출하면 분은 기본값 인 90으로 설정됩니다. 그런 다음 main 메서드는 문자열 만 사용하여 movies 메서드를 호출 할 수 있음을 보여 주며 문자열과 정수로 호출 할 수 있음을 보여줍니다.메서드를 사용하고 main 메서드에 값을 전달합니다.

static void Main() 
{ 
    Console.WriteLine("Movie title is {0}, and time is", MovieListing("x")); 
} 

private static string MovieListing(string name, int defaultTime = 60) 
{ 
    string Name, stringTime; 
    int time; 
    bool isValid; 
    Console.Write("What is the name of the movie?"); 
    Name = Console.ReadLine(); 
    Console.Write("What is the time of the movie? Default is 90 if left blank"); 
    stringTime = Console.ReadLine(); 
    time = Convert.ToInt32(stringTime);   
} 

그래서 필자는 그냥 기본 (90)를 사용하여 코드의 경우 죄송 주요 방법으로 다시 전달하는 경우 프로그램이 사용자가 시간 INT를 입력 한 경우 말해 그것을 사용하거나 갈 수있는 방법 빈 사고를 남겨 엉망이 많은 성공없이 다른 방법을 시도하고 있었다

+0

@VsevolodGoloviznin : 그는 이미 그걸 가지고 있습니다. –

+0

질문이 명확하지 않습니다. 사용자가 시간을 입력했는지 확인하는 방법은 stringTime이 비어 있지 않은지 확인하는 것입니다. 그것은 분명한 사실입니다. 왜 그런 질문을해야하는지 모르겠습니다. 그래서 무엇을 알아 내려고 정말로하고 있습니까? – theMayer

+0

함수가 리턴 argumet을 1 개만 가질 수 있으므로 두 값을 어떻게 반환해야합니까? 나는 당신이 ref/out을 사용해야한다는 것을 의심한다. 작업의 정확한 요구 사항을 질문에 반영하십시오. –

답변

4

입력 된 값이 비어있는 경우가 확인 삼항 작업을 사용할 수 있습니다

time = string.IsNullOrEmpty(stringTime) ? defaultTime : Convert.ToInt32(stringTime); 

그것은 구문 분석 채워진 경우 stringTime, 그렇지 않으면 기본 소요됩니다.

+1

제 의견으로는, 이것이 문제가 해결 된 최선의 방법입니다. –

+0

완전히 잊어 버린 IsNullOrEmpty! 고마워요 – Tril

2

여기에 간단한 Movie 개체를 사용하여 값을 저장하는 더 좋은 방법이 있습니다. 이 데모하고 입력에 대한 사용자 요청하는 두 개의 하드 라인을 출력한다 : 우리는 이동할 수있는 별도의 Movie 객체를 구축함으로써

private class Movie 
{ 
    private readonly int _defaultLength = 90; 

    public string Title { get; set; } 
    public int Length { get; set; } 

    // constructor without length - use default length 
    public Movie(string title) 
    { 
     this.Title = title; 
     this.Length = _defaultLength; 
    } 

    // constructor with both properties 
    public Movie(string title, int length) 
    { 
     this.Title = title; 

     // make sure Length is valid 
     if (length > 0) 
      this.Length =length; 
     else 
      this.Length = _defaultLength; 
    } 
} 

static void Main() 
{ 
    // make a Movie object without length 
    var shortMovie = new Movie("Zombieland"); 

    // make a Movie object and specify length 
    var longMovie = new Movie("Lawrence of Arabia", 216); 

    Console.WriteLine("{0} is {1} minutes long", shortMovie.Title, shortMovie.Length); 
    Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length); 

    // get input from user: title 
    Console.Write("What is the name of another movie?"); 
    var userTitle = Console.ReadLine(); 

    // get input from user: length 
    Console.Write("What is the length of {0}? Default is 90 if left blank", userTitle); 
    var userTime = Console.ReadLine(); 

    // try to convert user input to an int and call Movie constructor to create a new object 
    int userTimeConverted = 0; 
    Movie userMovie; 
    if (Int32.TryParse(userTime, out userTimeConverted)) 
    { 
     // make a new Movie object with the user's input 
     userMovie = new Movie(userTitle, userTimeConverted); 
    } 
    else 
    { 
     // make a new Movie object without the user's input 
     userMovie = new Movie(userTitle); 
    } 

    Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length); 
} 

를 기본 길이를 저장하고보고 확인에 필요한 로직의 대부분 또는 모든 길이가 Main() 메소드에서 유효하면. 이것은 훨씬 더 깨끗하고 읽기 쉬울 것입니다.

위의 코드에서 보여 주듯이 추가 보너스로 Movie의 인스턴스를 원하는만큼 만들 수 있습니다.

+0

네, 실제로 구문 분석을 해보는 것은 올바르게 처리하지 않고 제 의견으로는 잘못된 코딩입니다. 어쨌든 +1. 이 게시물에 대한 많은 작업을 수행했습니다. –

+0

'bool' 결과를 분기하거나 저장하지 않고 호출하는 것입니까? 그리고 감사합니다. 건배! –

+0

무언가를 분석하려고하면 항상 좋은/나쁜 결정이 있어야합니다. 이 경우 다른 생성자를 사용하는 것이 완전히 의미가 있습니다. –

0

기본값을 사용자가 입력하고 감지하고 처리 할 수 ​​없도록 설정하십시오.

private static string MovieListing(string name, int defaultTime = -1) 
{ 
    var isDefaultUsed = false; 
    if (defaultTime = -1) 
    { 
     isDefaultUsed = true; 
     defaultTime = 60; 
    } 
    string Name, stringTime; 
    int time; 
    bool isValid; 
    Console.Write("What is the name of the movie?"); 
    Name = Console.ReadLine(); 
    Console.Write("What is the time of the movie? Default is 90 if left blank"); 
    stringTime = Console.ReadLine(); 
    time = Convert.ToInt32(stringTime);   
} 
관련 문제