获取用户输入的字符并将其存储到变量中Java

问题描述

下面的代码获取用户在文本框中输入的字符串(来自 GUI)并将其存储到名为 aString 的变量中:

@Produces
@Singleton
@Requires(classes = {GlobalException.class,ExceptionHandler.class})
public class GlobalExceptionHandler implements ExceptionHandler<GlobalException,HttpResponse> {

    @Override
    public HttpResponse handle(HttpRequest request,GlobalException exception) {
        return HttpResponse.ok(0);
    }
}

public class GlobalException extends RuntimeException{
}

下面的代码不像上面的代码那样工作,因为它是一个字符而不是字符串。从用户那里获取字符(作为字符)并将其存储在变量中以供以后在程序中使用的另一种方法是什么?

aString = txtString.getText();

解决方法

如果你需要整个字符,你可以使用它:

String str = txtCharToString.getText().toString();
char[] aChar = str.toCharArray();

或者像这样,如果只是第一个字符:

char aChar = txtCharToString.getText().charAt(0);