[英]Replace a specific string character index into 0
我已经建立了一个表格图表应用程序。 我有一个带有动作事件的计算按钮。 因此,首先,该动作事件将从名为field的文本字段按钮获取getText。 之后,它将字符串转换为int。 但是,我想在将字符串转换为int之前检查一件事。 也就是说,我想检查字符串索引[0]是否等于'-',如果是,那么它将被更改为0。
if(text.charAt[0] == "-"){text.setCharAt(0, "0")}
但是说条件从char到string是不可比的。 还有其他方法可以将索引字符替换为0吗?
这是动作侦听器代码:
calculate = JButton; result = JTextArea; field = JTextField;
calculate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
result.setText(null);
String text = field.getText();
Integer i = Integer.valueOf(text);
for (int j = 1; j <= 10; j++){
result.append((i + " " + "x" + " " + j + "=" + " " +(i * j)) + "\n");
}});
我试过下面的代码,但我不知道如何将'text'分配给'str':
if(text.charAt(0) == '-'){
StringBuilder str = new StringBuilder(text);
str.setCharAt(0, '0');
}
此外; 当新字符串设置为'str'而不是'text'时,我无法将str分配为字符串,例如StringBuilder str = new StringBuilder(str);
因此; 我基本上陷入了这一行。
在:
text.charAt[0] == "-"
text.charAt[0]
是一个char 。 "-"
是一个String 。 而且,永远不要在字符或字符串上使用==
。 使用equals()
代替。
尝试
text.charAt[0].equals('-');
尝试if(text.charAt[0] == '-'){text.setCharAt(0, '0')}
“ a”-字符串
'a'-字符
text.charAt[0] == "-"
在此行中,检查字符串"-"
将其更改为'-'
代替==
,使用equals()
如下:
text.charAt[0].equals('-')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.