2013-10-01 4 views
3

GUI 프로그램을 만들고 있습니다. 첫 번째 프로그램에는 다음 코드가 있습니다.텍스트 필드에서 텍스트 가져 오기

double num1; 
num1 = Double.parseDouble(guess.getText()); 

이 코드는 텍스트 필드에서 값을 가져 와서 double 값으로 변환합니다.

어떻게 값을 가져 와서 String 또는 Char로 변환 할 수 있습니까?

답변

0

getText()은 이미 텍스트를 String으로 반환합니다. Btw, 구문 분석 오류로 인해 예외가 발생합니다. 하지만 옳은 길에. :)

0

getText() 메서드는 문자열을 반환합니다. .parseDouble을 사용할 때 사용자가 입력 한 문자열을 이중으로 변환하는 것이므로 문자열의 경우 호출 된 값이 이미 문자열이기 때문에 .parse 메서드를 사용할 필요가 없습니다. 문자의 경우이 같은 것을 사용하는 것 다음 getText() 이후

String text = jTextField1.getText(); 
if (text.length() > 1 && !text.contains(" ") && !text.contains(",")) { 
    //make sure that its length is not over 1, and that it has no spaces and no commas 
    char ch = text; 
} else { 
    //if a space or comma was found no matter how big the text it will execute the else.. 
    System.out.println("this is not allowed"); 
    jTextField1.setText(""); 
} 
+0

문자열 값으로 더블 변환하는 데 도움이됩니다. 무엇을 성취하려고 했습니까? – afsantos

+0

@afsantos 다음과 같은 것 : char abc = String; – Ayvadia

2

이미 String 사소한 같이 그 값을 저장하는 String 반환합니다.

double을 구문 분석하려면 이미 입력 했으므로 입력이 올바르지 않은 경우 NumberFormatException을주의 깊게 살펴보십시오.

값을 char으로 저장하려면 요구 사항에 따라 달라집니다. 첫 번째 캐릭터를 원하십니까? 문자열에 한 문자 만 있어야합니까? 어떤 캐릭터가 유효합니까? 등등.

// Storing the value as a String. 
String value = guess.getText(); 

// Storing the value as a double. 
double doubleValue; 
try { 
    doubleValue = Double.parseDouble(value); 
} catch (NumberFormatException e) { 
    // Invalid double String. 
} 

// Storing the value as a char. 
char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0; 

// Require the String to have exactly one character. 
if (value.length() != 1) { 
    // Error state. 
} 
char charValue = value.charAt(0); 
-1

getText() 함수는 이미 Textfield에서 String 값을 가져온다. 예를 들어

:

여기
String var = guess.getText(); 

, varTextfield로부터 수신 String 값을 저장한다.

1

사용 한 String.valueOf() 대신에 사용해 Double.parseDouble의()이 당신이`char` 경우에 대한 귀하의 논리가 조금 혼란 보인다

관련 문제