2015-02-05 2 views
1

예를 들어 (학교) 학년을 텍스트로 변환하는 간단한 Windows Form 응용 프로그램 (Visual Studio 2013)을 만들려고합니다. 1 -> "매우 좋음"등으로 입력하십시오.숫자가 X와 Y 사이 인 경우

private void btn_note_Click(object sender, EventArgs e) 
{ 
     if (txtb_note.Text == "1") 
     { 
      lbl_ergebnis.Text = "very good"; 
     } 

     if (txtb_note.Text == "2") 
     { 
      lbl_ergebnis.Text = "good"; 
     } 

     // Etc... 
} 

등등. 하지만 99 또는 일부 텍스트를 입력하면 "잘못된 입력"이 표시되어야한다고 덧붙이고 싶습니다.

하지만 어떻게 할 수 있습니까? I've는

에 대한
if (txtb_note.Text == "?????") 
{ 
     if (txtb_note.Text == "1") 
     { 
      lbl_ergebnis.Text = "very good"; 
     } 
} 
else 
{ 
    lbl_ergebnis.Text = "invalid"; 
} 

을 시도 ????? 나는 "1과 6 사이의 숫자"라는 것을 필요로합니다. 그래서 7은 "무효"합니다. 거기서 무엇을 사용할 수 있습니까?

내 문제를 이해 하시길 바랍니다.

본인 : C# 및 Visual Studio의 새로운 기능입니다.

+3

* numbers *를 처리하려는 경우 * 문자열 *이있는 순간에는 문자열을 구문 분석해야합니다. 'Int32.TryParse'는 아마도 좋은 출발일 것입니다 ... –

+0

btw : 열거자인 – jean

+1

을 또 다른 변형으로 볼 수 있습니다 : [switch] (https://msdn.microsoft.com/en-us/library/06tc147t) .aspx) like'switch (txtb_note.Text) {case "1": ... break; case "2": ... 휴식; ...; ' – Grundy

답변

2

다른 답변에도이를 수행하는 방법이 나와 있지만. 나는 그들에게 조언 할 것이고, 나는 올바른 도구를 사용할 것이다.

당신이 원하는 무엇을, 개념적, 문자열, 성적 (정수)를 변환하는 사전, 그래서 나는 그 길 갈 것 : 당신이 특정 경우

// We are going to use integer keys, with string values 
    var stringGrades = new Dictionary<int, string>() 
    { 
    {1, "good"}, // 1 is the Key, "good" is the Value 
    {2, "decent"}, 
    {3, "bad"} 
    }; 

    int integerGrade; 
    string textGrade; 
    // try to convert the textbox text to an integer 
    if(!Int32.TryParse(txtb_note.Text, out integerGrade) 
    // if successful, try to find the resulting integer 
    // (now in "integerGrade") among the keys of the dictionary 
    || !stringGrades.TryGetValue(integerGrade, out textGrade)) 
    // Any of the above conditions weren't successful, so it's invalid 
    lbl_ergebnis.Text = "Invalid value"; 
    else 
    // It worked, so now we have our string value in the variable "textGrade" 
    // obtained by the "out textGrade" parameter on TryGetValue 
    lbl_ergebnis.Text = textGrade; 

을 텍스트 상자에서 문자열로 원래의 등급을 사용하여, 그래서 그 경로를 이동하는 것은 당신이 선호하는 경우 :

// This time, we directly use string as keys 
    var stringGrades = new Dictionary<string, string>() 
    { 
    {"1", "good"}, 
    {"2", "decent"}, 
    {"3", "bad"} 
    }; 

    string textGrade; 
    // Try to get the value in the dictionary for the key matching the text 
    // on your textbox, no need to convert to integer 
    if(!stringGrades.TryGetValue(txtb_note.Text, out textGrade)) 
    lbl_ergebnis.Text = "Invalid value"; 
    else 
    lbl_ergebnis.Text = textGrade; 

TryGetValue 이후와 out 매개 변수를 혼동 할 수 있습니다, 여기 쉬울 수 있습니다 그것을 할 수있는 또 다른 방법은,이다

: 당신이 싶어 루프 루프처럼, 한 줄의 코드로 번역 될 수 있다면

// If our dictionary doesn't contain the key we are looking for, 
    // the input is invalid 
    if(!stringGrades.ContainsKey(txtb_note.Text)) 
    lbl_ergebnis.Text = "Invalid value"; 
    else 
    // it contains the key, so let's show its value: 
    lbl_ergebnis.Text = stringGrades[txtb_note.Text]; 

어느 : 당신이 프로그래밍에 새로운 경우 읽기 (우리는 위와 같은 <string, string> 사전을 사용합니다)

lbl_ergebnis.Text = stringGrades.ContainsKey(txtb_note.Text) ? 
     stringGrades[txtb_note.Text] : "Invalid value"; 

다른 방법

( switch 또는 if-else 사용) 작업 (내가 말했듯이 그건 그냥 "루프를 반복"이야,이 마지막 코드에 의해 혼란스러워하지 않음)가 아니라 있습니다 오른쪽 t ool. 개념적으로 생각하고 원하는 것은 값을 다른 값으로 변환하는 것입니다. 사전이며 .NET ( Dictionary<T,T2> 클래스)에 해당 도구가 있습니다.

향후 다른 성적이 필요한 경우, 사전에 추가하면 문자열을 변환하는 코드가 계속 작동합니다. 또한 사전을 코드에 저장할 필요가 없습니다. 텍스트 파일, 웹 서비스, 데이터베이스 등에서 검색 할 수 있으며 응용 프로그램을 다시 컴파일하지 않고도 사용할 수 있습니다.

+0

나는 OP 작성자가 프로그래밍에 익숙하지 않았기 때문에 그것이 무엇을하고 있는지 보여주는 코드를 주석 달기 위해 편집했습니다. ** 강하게 ** 생산 코드에서 이와 같은 코멘트를 막을 것입니다. (코드를 쉽게 읽을 수 있다면, 그 코드가하는 일에 대해 언급 할 필요가 없습니다.) – Jcl

+0

이것은 가장 좋은 답변입니다. TryGetValue가있는 사전 –

1

switch 문을 사용해 보셨습니까? 그래서

 string result; 
     switch (txtb_note.Text) 
     { 
      case "1": 
       result = "Very Good"; 
       break; 
      case "2": 
       result = "Good"; 
       break; 
      case "3": 
       result = "Normal"; 
       break; 
      case "4": 
       result = "Below Normal"; 
       break; 
      case "5": 
       result = "If you were Asian you would be dishonored"; 
       break; 
      default: 
       result = "Invalid Number"; 
       break; 
     } 
     return result; 

+2

return 문 다음에 쉬지 않아도됩니다. –

+0

그래, 그가 프로그래밍에 익숙하지 않고 switch 문을 모르고 다시 사용하려고하면 오류 및 이유를 모르겠다, 그래서 거기에 그것을두고, 그 누구도 죽일 텐데 – Patrick

+0

@ 패트릭 도달 할 수없는 코드는 도달 할 수없는 코드입니다, 프로그래밍에 초보자가 아니든 상관 없습니다. 나는 코드에서 그것을 제거 할 것이다. (만약 당신이 그에게'switch' 문을 가르치고 싶다면 올바른 사용법을 보여주는 아래에 주석을 추가한다.) – Jcl

0

사용할 수있는 "잘못된 번호를"기본에 해당하고 반환하는 경우에 설정되지 않은 이런 식으로 모든 것을 같은 "만약 ... 다른 사람"또는 "스위치" 예를

if (txtb_note.Text == "1") 
{ 
    lbl_ergebnis.Text = "very good"; 
} 
else if (txtb_note.Text == "2") 
{ 
    lbl_ergebnis.Text = "good"; 
} 
... 
else 
{ 
    lbl_ergebnis.Text = "invalid"; 
} 
에 대한
+0

그건 내 첫 번째 생각 이었지만, 1-5는 무효라고 말했습니다. 단지 6 명이 "불충분하다"고합니다. – Jan

+0

그건 불가능합니다. 중단 점을 설정하고 단일 단계로 기능을 디버깅 할 수 있습니다. – happybai

0

먼저 당신의 int로 변환 할 필요가! 아마도 과 같은 것을 시도해보십시오.

try{ 
int gradeNumber = int.Parse(txtb_note.Text); 
if(gradeNumber > 6) MessageBox.Show("Please enter a number between 1 and 6!"); 
else if(gradeNumber == 1) lbl_ergebnis.Text = "very good"; 
else if(gradeNumber == 2) lbl_ergebnis.Text = "good"; 
// and so on :) 
} 
catch(Exception){ 
MessageBox.Show("please enter a valid int!"); 
} 
+2

예외를 throw하는 대신 TryParse를 먼저 수행해야합니다. –

1

넌 그냥 if-else if-else

if (txtb_note.Text == "1") 
{ 
    lbl_ergebnis.Text = "very good"; 
} 
else if (txtb_note.Text == "2") 
{ 
    lbl_ergebnis.Text = "good"; 
} 
else 
{ 
    lbl_ergebnis.Text = "invalid"; 
} 

아니면 switch

switch(txtb_note.Text) 
{ 
    case "1": 
     lbl_ergebnis.Text = "very good"; 
     break; 
    case "2": 
     lbl_ergebnis.Text = "good"; 
     break; 
    default: 
     lbl_ergebnis.Text = "invalid"; 
     break; 
} 

그런 다음 당신은 또한 다른 옵션을 허용하는 int에 문자열을 구문 분석 고려해야 사용할 수 있습니다.

int val; 
if(!int.TryParse(txtb_note.Text, out val) 
{ 
    lbl_ergebnis.Text = "Not a valid integer"; 
} 
else 
{ 
    if(val >= 0 && val <=4) 
     lbl_ergebnis.Text = "Bad"; 
    // Additional conditions. 
} 
0

로직에 대해 생각해보십시오. 1. 텍스트 상자 값을 정수로 변환하십시오. 2. 1과 7의 수를 비교하십시오.

int value = 0; 
//TryParse returns true if the string can be converted to integer and converts the string to integer and pass to variable "value" 
if(Integer.TryParse(txtb_note.Text, out value)) 
{ 
    if(value > 1 && value < 7) 
     lbl_ergebnis.Text = "very good"; 
else lbl_ergebnis.Text = "invalid"; 
} 
else lbl_ergebnis.Text = "invalid"; 
0

간단합니다. 사용해보기 :

private void btn_note_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      int score = int.Parse(txtb_note.Text); 
     if (score >=1 && score <7) 
     { 
      if (score == 1) 
      { 
       lbl_ergebnis.Text = "very good"; 
      } 
      . 
      . 
      . 
      // Keep going to 6 
     } 
     else 
     { 
      lbl_ergebnis.Text = "invalid"; 
     } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 

또한 switch을 사용할 수 있습니다.

private void btn_note_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      int score = int.Parse(txtb_note.Text); 
     switch (score) 
     { 
      case "1": 
       score = "Very Good"; 
       break; 
      case "2": 
       score = "Good"; 
       break; 
       . 
       . 
       . 
       . 
       // Keep going to 6 
      default: 
       score = "invalid"; 
       break; 
     } 
     return score; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 
+0

입력이 정수가 아니면 처리되지 않은 예외가 발생합니다. – juharr

+0

@juharr 답변을 업데이트했습니다. – aliboy38